Model Associations

Share:

Listens: 0

Rails Coach

Technology


ActiveRecord models are based upon tables in relational databases. This, of course, means that they can be relational. Models can associate in three main ways: one to many, one to one, and many to many. One to many is usually achieved by calling has_many on the model representing the “one” to state that it “has many” of its counterparts. The model that represents the “many” calls belongs_to . Here’s an example: class User < ActiveRecord::Base has_many :posts end class Post < ActiveRecord::Base belongs_to :user end In addition, the model that represents the “many” needs a reference column or foreign key for the “one”. In this case, the posts table would have a user_id column. One to one works the same way one to many works except it uses has_one instead of has_many. Many to many is implemented in one of two different ways. The first--and generally default--way of doing this is has_and_belongs_to_many. As you can imagine, this is used just like has_many or belongs_to except you call it in both models. class Tag < ActiveRecord::Base has_and_belongs_to_many :posts end class Post < ActiveRecord::Base has_and_belongs_to_many :tags end