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