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 ...

Get Ruby on Rails® for Microsoft Developers now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.