Active Record associations can be used to describe one-to-one, one-to-many and many-to-many relationships between models. Each model uses an association to describe its role in the relation. The belongs_to association is always used in the model that has the foreign key.
(1) One-to-one
Use has_one in the base and belongs_to in the associated model.
models/employee.rb
has_one :address
models/address.rb
belongs_to :employee #foreign key – employee_id
end
(2) One-to-many
Use has_many in the base, and belongs_to in the associated model.
models/user.rb
has_many :events
models/event.rb
belongs_to :user #foreign key – user_id
(3) Many-to-Many
There are two different ways to set up a many-to-many association in Rails.
1. has_and_belongs_to_many (often reffered to as habtm)
In migration
def self.up
models/product.rb
has_and_belongs_to_many :categories
models/category.rb
has_and_belongs_to_many :products
Here join table ‘categories_products’ contains primary keys of both the tables. The table name follows alphabetical order of each table, separated by an underscore.
2. has_many :through
models/categorization.rb
belongs_to :product
belongs_to :category
models/product.rb
has_many :categorizations
has_many :categories, :through => :categorizations
models/category.rb
has_many :categorizations
has_many :products, :through => :categorizations
This technique is used when you want to put some additional fields in median table. Here categorization is a full model that represent the join table.
So, with these tips you can choose the right one for your project.
Sorry, comments are closed for this article.