Recall & Review
beginner
What does
has_many :through do in Rails?It sets up a many-to-many connection with another model through a third model, allowing you to work with the join model directly.
Click to reveal answer
intermediate
Why use
has_many :through instead of has_and_belongs_to_many?Because
has_many :through lets you add extra data or behavior to the join model, while has_and_belongs_to_many is simpler but limited.Click to reveal answer
beginner
In a many-to-many setup with
has_many :through, what role does the join model play?The join model connects the two main models and can hold extra information about their relationship.
Click to reveal answer
intermediate
How do you define a many-to-many relationship between
Author and Book using has_many :through?Create a join model like
Authorship with belongs_to :author and belongs_to :book. Then in Author use has_many :authorships and has_many :books, through: :authorships. Similarly in Book use has_many :authorships and has_many :authors, through: :authorships.Click to reveal answer
intermediate
What is a practical example of extra data you might store in a join model?
For example, in an
Authorship join model, you might store the role of the author (like 'editor' or 'writer') or the date they started collaborating.Click to reveal answer
Which association allows adding extra attributes to the join table in a many-to-many relationship?
✗ Incorrect
has_many :through uses a join model where you can add extra attributes. has_and_belongs_to_many does not support this.In Rails, what must you create to use
has_many :through?✗ Incorrect
You need a join model that belongs to both associated models to use
has_many :through.If
Author has many Books through Authorships, which is true?✗ Incorrect
Author has many Authorships, and each Authorship belongs to a Book.Which is NOT a benefit of using
has_many :through?✗ Incorrect
has_many :through is more complex to set up than has_and_belongs_to_many.What is the correct way to declare a many-to-many association in the join model?
✗ Incorrect
The join model uses
belongs_to for each associated model.Explain how to set up a many-to-many relationship using
has_many :through in Rails.Think about the roles of the join model and the main models.
You got /3 concepts.
Describe the advantages of using
has_many :through over has_and_belongs_to_many.Consider what you can do with the join model.
You got /3 concepts.