This document discusses one-to-one, one-to-many, and many-to-many relationships in Active Record. One-to-one relationships involve a belongs_to and has_one association, like users and profiles. One-to-many relationships are common, like users having many orders. Many-to-many relationships use a join table to connect two models, such as writing prompts belonging to multiple categories. The document provides guidance on when to use each type of relationship.
3. One to One
▪ The table of the belongs_to
model contains a column with
the foreign key (often id) of the
has_one model
▪ Not always clear when to use
one
▪ Users and social media profiles
– A user only has_one Facebook
profile, and that profile only
belongs_to that user
4.
5. So when do I use it?
One indicator: the potential for
a lot of null (empty) fields
6. One to Many
▪ Very common relationship
▪ Like one to one, the table of the belongs_to model contains a column
with the foreign key (often id) of the has_many model
▪ Users and orders
– A user has_many orders, and each order only belongs_to that user
7.
8.
9. Many to Many
▪ Also very common
▪ Writing prompts and categories
– Categories can contain many prompts, and those prompts can belong to many
categories
▪ Two ways of describing the relationship
– has_many JOINTABLE & has_manyOTHERTABLE through JOINTABLE
– has_and_belongs_to_many (Rails/ActiveRecord magic creates the join table)
▪ Join table contains the foreign keys (ids) of what's connected to it
10.
11. When to use has_and_belongs_to_many
When your join table only contains the foreign keys(ids)
and no other useful information
12. When to use has_and_belongs_to_many
When your join table only contains the foreign keys(ids)
and no other useful information
not conventional
13. When to use has_and_belongs_to_many
When your join table only contains the foreign keys(ids)
and no other useful information
14. t.what_now?
▪ t.belongs_to, t.references, and t.integer
– Everyone has their own preference, but any of these will work
– t.belongs_to :user
– t.references :user
– t.integer :user_id
▪ Note: when you use t.integer you need to specify the id because integer just means a
number
▪ With t.belongs_to or t.references the Rails/ActiveRecord magic can safely assume
what you mean