Recall & Review
beginner
What is a polymorphic association in Rails?
A polymorphic association lets a model belong to more than one other model using a single association. It uses a type and an ID to link to different models through one interface.
Click to reveal answer
beginner
How do you declare a polymorphic belongs_to association in Rails?
Use
belongs_to :attachable, polymorphic: true in the model that belongs to multiple other models.Click to reveal answer
beginner
What columns are required in the database for a polymorphic association?
You need two columns: one for the ID (e.g., <code>attachable_id</code>) and one for the type (e.g., <code>attachable_type</code>) to store the associated model's class name.Click to reveal answer
intermediate
How do you set up the other side of a polymorphic association?
Use
has_many :attachments, as: :attachable in the models that can have attachments. The as: option tells Rails this is a polymorphic interface.Click to reveal answer
intermediate
Why use polymorphic associations instead of multiple separate associations?
Polymorphic associations reduce code duplication and database complexity by allowing one model to relate to many others without needing separate foreign keys or tables for each.
Click to reveal answer
Which two columns are essential for a polymorphic association in Rails?
✗ Incorrect
Rails uses
attachable_id to store the associated record's ID and attachable_type to store the class name.How do you declare a polymorphic association on the model that belongs to multiple models?
✗ Incorrect
The model that belongs to multiple others uses
belongs_to :attachable, polymorphic: true.What does the
as: option do in a has_many association?✗ Incorrect
The
as: option tells Rails the name of the polymorphic interface to use.Which of these is a benefit of polymorphic associations?
✗ Incorrect
Polymorphic associations let one model relate to many others through a single association, simplifying code.
If a Comment model belongs to either a Post or a Photo, what would the polymorphic association look like in Comment?
✗ Incorrect
The Comment model uses
belongs_to :commentable, polymorphic: true to belong to either Post or Photo.Explain how polymorphic associations work in Rails and why they are useful.
Think about how one model can connect to many different models using one link.
You got /5 concepts.
Describe the database setup needed to support a polymorphic association in Rails.
Focus on the columns that store the link to other models.
You got /4 concepts.