Skip to content

Instantly share code, notes, and snippets.

@jnewman12
Created January 10, 2017 09:35
Show Gist options
  • Select an option

  • Save jnewman12/d8db139108672da03ded92d8c013b5a6 to your computer and use it in GitHub Desktop.

Select an option

Save jnewman12/d8db139108672da03ded92d8c013b5a6 to your computer and use it in GitHub Desktop.
Rails Multi Model Associations

Rails Multi Model Associations


Objectives

  • Understand Model Relationships, and how they relate to application data
  • Understand has_many, has_one, and belongs_to

Why Associations?

  • In Rails, an association is a connection between two Active Record models.
  • Why do we need associations between models? Because they make common operations simpler and easier in your code.
  • For example, consider a simple Rails application that includes a model for authors and a model for books. Each author can have many books.
  • Without associations, the model declarations would look like this:
class Author < ApplicationRecord
end
 
class Book < ApplicationRecord
end
  • Now, suppose we wanted to add a new book for an existing author. We'd need to do something like this:
@book = Book.create(published_at: Time.now, author_id: @author.id)
  • or consider deleting an author, and assuring all the authors books get deleted as well
@books = Book.where(author_id: @author.id)
@books.each do |book|
  book.destroy
end
@author.destroy
  • With Active Record associations, we can streamline these operations by declaratively telling Rails that there is a connection between the two models.
  • Here's the revised code for setting up authors and books:
class Author < ApplicationRecord
  has_many :books, dependent: :destroy
end
 
class Book < ApplicationRecord
  belongs_to :author
end
  • With this change, creating a new book for a particular author is easier:
@book = @author.books.create(published_at: Time.now)
  • Deleting an author and all of its books is much easier:
@author.destroy

Types of Associations

  • Rails supports 6 types of associations

    • belongs_to
    • has_one
    • has_many
    • has_many :through
    • has_one :through
    • has_and_belongs_to_many
  • For right now, we are only going to be focusing on 3 of them

    • belongs_to
    • has_one
    • has_many
  • Associations are created using special calls (methods) that allow us to add these features onto our models

  • For example, by declaring that one model belongs_to another, you instruct Rails to maintain Primary Key-Foreign Key information between instances of the two models, and you also get a number of utility methods added to your model


The belongs_to association

  • A belongs_to association sets up a one-to-one connection with another model, such that each instance of the declaring model "belongs to" one instance of the other model.
  • For example, if your application includes authors and books, and each book can be assigned to exactly one author, you'd declare the book model this way:
class Book < ActiveRecord::Base
  belongs_to :author
end

belongs_to

  • to create a migration file for this association, it might look something like the following
class CreateBooks < ActiveRecord::Migration
  def change
    create_table :authors do |t|
      t.string :name
      t.timestamps
    end
 
    create_table :books do |t|
      t.belongs_to :author, index: true
      t.datetime :published_at
      t.timestamps
    end
  end
end

The has_one association

  • A has_one association also sets up a one-to-one connection with another model, but with somewhat different semantics.
  • This association indicates that each instance of a model contains or possesses one instance of another model.
  • For example, if each supplier in your application has only one account, you'd declare the supplier model like this:
class Supplier < ActiveRecord::Base
  has_one :account
end

has one

  • a corresponding migration file might look something like the following
class CreateSuppliers < ActiveRecord::Migration
  def change
    create_table :suppliers do |t|
      t.string :name
      t.timestamps
    end
 
    create_table :accounts do |t|
      t.belongs_to :supplier, index: true
      t.string :account_number
      t.timestamps
    end
  end
end

The has_many association

  • A has_many association indicates a one-to-many connection with another model.
  • You'll often find this association on the "other side" of a belongs_to association.
  • This association indicates that each instance of the model has zero or more instances of another model.
  • For example, in an application containing authors and books, the author model could be declared like this:
class Author < ActiveRecord::Base
  has_many :books
end
  • note: The name of the other model is pluralized when declaring a has_many association.

has many

  • a corresponding migration for this association might look something like this
class CreateAuthors < ActiveRecord::Migration
  def change
    create_table :authors do |t|
      t.string :name
      t.timestamps
    end
 
    create_table :books do |t|
      t.belongs_to :author, index: true
      t.datetime :published_at
      t.timestamps
    end
  end
end

Wrap up

  • here we saw 3 of the most common rails associations and how they relate to our data
  • we saw the re-emphasis on primary/foreign keys, and how they relate to our data in rails
  • we saw just 1 way for how to generate these relationships in our migrations

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment