0
0
Ruby on Railsframework~5 mins

Polymorphic associations in Ruby on Rails - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
Aattachable_key and attachable_name
Battachable_id and attachable_type
Cattachable_key and attachable_type
Dattachable_id and attachable_name
How do you declare a polymorphic association on the model that belongs to multiple models?
Abelongs_to :attachable, polymorphic: true
Bhas_one :attachable, polymorphic: true
Chas_many :attachable, polymorphic: true
Dbelongs_to :attachable
What does the as: option do in a has_many association?
ADeclares a scope
BSpecifies the foreign key name
CSets the table name
DDefines the polymorphic interface name
Which of these is a benefit of polymorphic associations?
AThey simplify code by using one association for many models
BThey require more database tables
CThey prevent models from sharing associations
DThey only work with one model
If a Comment model belongs to either a Post or a Photo, what would the polymorphic association look like in Comment?
Ahas_many :commentable, polymorphic: true
Bbelongs_to :post_or_photo
Cbelongs_to :commentable, polymorphic: true
Dhas_one :commentable
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.