has_one
The simplest database relationship is the one-to-one
relationship. With Active Record, you can implement one-to-one
relationships with belongs_to or
has_one. You’ll decide which to use
based on where the foreign key lands. For example, if an Address belonged to a Person, the addresses table would need a person_id column. Person would use a has_one relationship. Figure 4-3 shows a has_one relationship.

Figure 4-3. In this one-to-one relationship, a Photo has_one File
Let’s take a simple example. Hypothetically, you could have decided
to implement photos and files in separate tables. If you put a foreign key
called photo_id into the files table, you would have this Active Record
Photo class:
class Photo < ActiveRecord::Base has_one :file ... end
has_one is identical to belongs_to with respect to metaprogramming. For
example, adding has_one :photo or
belongs_to :photo to Slide would add the photo attribute to Slide. But the Photo Share application does not
need a separate table to manage files, so let’s move on to that marathon
of typing, has_and_belongs_to_many.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access