basic ruby on rails cardinality and associations

Basic Ruby on Rails Cardinality and Associations

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

Basic Ruby on Rails Cardinality and Associations

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

Syndicate content