O'Reilly logo

Ruby on Rails® for Microsoft Developers by Antonio Cangiano

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

7.5. ActiveRecord Associations

Associations are highly readable class methods used to define relationships between models, allowing you to easily work with associated objects. The convenience of Book.find_by_title("On the Road").author.name is only possible thanks to the fact that you established a relationship between the Book and Author class models through a pair of association methods. By employing them (has_many and belongs_to), and respecting the foreign key naming convention by adding an author_id column to the books table, you automatically obtained several methods that are added to instances of both models, including author, which returns the Author object for any given Book object.

The association methods are:

  • belongs_to

  • has_one

  • has_many

  • has_and_belongs_to_many

These ActiveRecord associations are used to define three types of relationships between models: one-to-one, one-to-many, and many-to-many. These are covered in the next few sections.

7.5.1. One-to-one Relationships

One-to-one relationships are relationships in which one row in a certain table references one row (at most) of the related table; so it could also reference no rows. A one-to-one relationship between models can be established by employing the has_one and belongs_to association methods. It is common for newcomers to confuse which model should have which of the two methods in their definition. The rule is rather clear though: use belongs_to in the definition of the model whose corresponding table has the ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required