0
0
Ruby on Railsframework~5 mins

Many-to-many with has_many through in Ruby on Rails - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
Ahas_many :through
Bhas_and_belongs_to_many
Cbelongs_to
Dhas_one
In Rails, what must you create to use has_many :through?
AA migration without a model
BA join model with <code>belongs_to</code> associations
CA database view
DA controller
If Author has many Books through Authorships, which is true?
AAuthor belongs to Authorship
BBook has many Authors through Authorships
CAuthor has many Authorships, and Authorship belongs to Book
DAuthorship has many Authors
Which is NOT a benefit of using has_many :through?
ASimpler setup than <code>has_and_belongs_to_many</code>
BEasier to add extra fields to the relationship
CMore control over the join model
DAbility to add validations on the join model
What is the correct way to declare a many-to-many association in the join model?
Abelongs_to_many :model1 and belongs_to_many :model2
Bhas_many :model1 and has_many :model2
Chas_one :model1 and has_one :model2
Dbelongs_to :model1 and belongs_to :model2
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.