Bird
Raised Fist0
Ruby on Railsframework~10 mins

Polymorphic associations in Ruby on Rails - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Polymorphic associations
Define polymorphic model
↓
Add polymorphic reference to other models
↓
Create records linking to different models
↓
Access associated records via polymorphic interface
↓
Use polymorphic methods to get related objects
Shows how a model can belong to multiple other models through a single interface using polymorphic references.
Execution Sample
Ruby on Rails
class Comment < ApplicationRecord
  belongs_to :commentable, polymorphic: true
end

class Post < ApplicationRecord
  has_many :comments, as: :commentable
end

class Image < ApplicationRecord
  has_many :comments, as: :commentable
end
Defines a Comment model that can belong to different models like Post or Image using polymorphic association.
Execution Table
StepActionEvaluationResult
1Create Post recordPost.create(title: 'Hello')Post with id=1 created
2Create Comment linked to PostComment.create(body: 'Nice post', commentable: Post#1)Comment with id=1 linked to Post#1
3Create Image recordImage.create(name: 'Pic')Image with id=1 created
4Create Comment linked to ImageComment.create(body: 'Great image', commentable: Image#1)Comment with id=2 linked to Image#1
5Access commentable of Comment#1Comment.find(1).commentableReturns Post#1
6Access commentable of Comment#2Comment.find(2).commentableReturns Image#1
7Access comments of Post#1Post.find(1).commentsReturns Comment#1
8Access comments of Image#1Image.find(1).commentsReturns Comment#2
9ExitNo more actionsPolymorphic links established and accessible
💡 All polymorphic associations created and verified
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4After Step 5Final
Post#1nilPost(id=1, title='Hello')Post(id=1, title='Hello')Post(id=1, title='Hello')Post(id=1, title='Hello')Post(id=1, title='Hello')Post(id=1, title='Hello')
Image#1nilnilnilImage(id=1, name='Pic')Image(id=1, name='Pic')Image(id=1, name='Pic')Image(id=1, name='Pic')
Comment#1nilnilComment(id=1, body='Nice post', commentable=Post#1)Comment(id=1, body='Nice post', commentable=Post#1)Comment(id=1, body='Nice post', commentable=Post#1)Comment(id=1, body='Nice post', commentable=Post#1)Comment(id=1, body='Nice post', commentable=Post#1)
Comment#2nilnilnilnilComment(id=2, body='Great image', commentable=Image#1)Comment(id=2, body='Great image', commentable=Image#1)Comment(id=2, body='Great image', commentable=Image#1)
Key Moments - 3 Insights
Why does Comment belong_to :commentable instead of a specific model like Post?
Because :commentable is polymorphic, Comment can link to different models (Post, Image, etc.) using the same interface, as shown in steps 2 and 4 where comments link to different models.
How does Rails know which model a comment belongs to?
Rails uses two columns: commentable_type (model name) and commentable_id (record id). This is why in step 5 accessing commentable returns the correct model instance.
Can we access comments from both Post and Image models?
Yes, because both models declare has_many :comments, as: :commentable, so steps 7 and 8 show accessing comments from different models.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what does Comment#1's commentable refer to at step 5?
AImage#1
BPost#1
CComment#2
Dnil
💡 Hint
Check step 5 in the execution_table where Comment#1's commentable is accessed.
At which step is a Comment linked to an Image created?
AStep 4
BStep 6
CStep 2
DStep 8
💡 Hint
Look for the step where Comment.create links to Image#1 in the execution_table.
If we add a new model Video with comments, which part of the flow changes?
ADefine polymorphic model
BCreate records linking to different models
CAdd polymorphic reference to Video
DAccess associated records
💡 Hint
Adding a new model requires adding polymorphic references to that model, as shown in the concept_flow step 2.
Concept Snapshot
Polymorphic associations let a model belong to multiple other models through one interface.
Use belongs_to :name, polymorphic: true in the polymorphic model.
Other models use has_many :name, as: :name to link.
Rails stores type and id to track the association.
Access related objects via the polymorphic interface transparently.
Full Transcript
Polymorphic associations in Rails allow one model to belong to more than one other model using a single association. For example, a Comment can belong to a Post or an Image. This is done by adding belongs_to :commentable, polymorphic: true in the Comment model. The Post and Image models then declare has_many :comments, as: :commentable. When creating comments, Rails stores the type of the associated model and its id. This lets you access the associated object easily, like comment.commentable returning either a Post or Image instance. This approach avoids creating separate associations for each model and keeps code flexible and clean.

Practice

(1/5)
1. What is the main purpose of polymorphic associations in Rails?
easy
A. To allow a model to belong to more than one other model using a single association
B. To create a one-to-one relationship between two models
C. To enforce database constraints on foreign keys
D. To automatically generate views for multiple models

Solution

  1. Step 1: Understand polymorphic association concept

    Polymorphic associations let one model belong to multiple other models through a single interface.
  2. Step 2: Compare options with concept

    To allow a model to belong to more than one other model using a single association correctly describes this flexibility. Other options describe unrelated features.
  3. Final Answer:

    To allow a model to belong to more than one other model using a single association -> Option A
  4. Quick Check:

    Polymorphic association = flexible belongs_to [OK]
Hint: Polymorphic means one interface for many models [OK]
Common Mistakes:
  • Thinking it creates one-to-one relationships
  • Confusing with database foreign key constraints
  • Assuming it auto-generates views
2. Which of the following is the correct syntax to declare a polymorphic belongs_to association in a Rails model?
easy
A. has_many :commentable, polymorphic: true
B. has_one :commentable, polymorphic: true
C. belongs_to :commentable, as: :polymorphic
D. belongs_to :commentable, polymorphic: true

Solution

  1. Step 1: Recall belongs_to polymorphic syntax

    The correct syntax uses belongs_to :name, polymorphic: true in the model that belongs to multiple types.
  2. Step 2: Match options with syntax

    belongs_to :commentable, polymorphic: true matches this exactly. Options A and D use wrong association types, and C uses incorrect keyword.
  3. Final Answer:

    belongs_to :commentable, polymorphic: true -> Option D
  4. Quick Check:

    belongs_to with polymorphic: true = belongs_to :commentable, polymorphic: true [OK]
Hint: belongs_to uses polymorphic: true, has_many uses as: :name [OK]
Common Mistakes:
  • Using has_many instead of belongs_to for polymorphic
  • Using 'as: :polymorphic' instead of 'polymorphic: true'
  • Confusing has_one with belongs_to
3. Given these models:
class Comment < ApplicationRecord
  belongs_to :commentable, polymorphic: true
end

class Post < ApplicationRecord
  has_many :comments, as: :commentable
end

class Photo < ApplicationRecord
  has_many :comments, as: :commentable
end

What will post.comments.first.commentable_type return if the first comment belongs to a Post?
medium
A. "Photo"
B. "Comment"
C. "Post"
D. nil

Solution

  1. Step 1: Understand polymorphic type storage

    The polymorphic association stores the class name of the associated object in commentable_type.
  2. Step 2: Identify the associated model

    The comment belongs to a Post, so commentable_type will be "Post".
  3. Final Answer:

    "Post" -> Option C
  4. Quick Check:

    commentable_type stores class name = "Post" [OK]
Hint: commentable_type holds the class name of associated model [OK]
Common Mistakes:
  • Confusing commentable_type with comment class
  • Expecting the associated object instead of its type string
  • Assuming nil if association exists
4. You have this model:
class Picture < ApplicationRecord
  belongs_to :imageable, polymorphic: true
end

Which of these will cause an error when creating a Picture?
medium
A. Picture.create(imageable_type: nil, imageable_id: 2)
B. Picture.create(imageable_type: "Product", imageable_id: 2)
C. Picture.create(imageable_type: "User", imageable_id: 1)
D. Picture.create(imageable_type: "User", imageable_id: 3)

Solution

  1. Step 1: Check required polymorphic keys

    Polymorphic belongs_to requires both imageable_type and imageable_id to be present for a valid association.
  2. Step 2: Identify missing or nil values

    Picture.create(imageable_type: nil, imageable_id: 2) has imageable_type: nil, which breaks the association and causes an error.
  3. Final Answer:

    Picture.create(imageable_type: nil, imageable_id: 2) -> Option A
  4. Quick Check:

    Missing polymorphic type causes error [OK]
Hint: Both type and id must be present for polymorphic belongs_to [OK]
Common Mistakes:
  • Assuming nil imageable_type is acceptable
  • Ignoring missing type causes runtime error
  • Confusing polymorphic keys with normal foreign keys
5. You want to add comments to both Articles and Events using polymorphic associations. Which setup correctly models this?
hard
A. class Comment < ApplicationRecord belongs_to :article belongs_to :event end
B. class Comment < ApplicationRecord belongs_to :commentable, polymorphic: true end class Article < ApplicationRecord has_many :comments, as: :commentable end class Event < ApplicationRecord has_many :comments, as: :commentable end
C. class Comment < ApplicationRecord has_many :articles has_many :events end
D. class Article < ApplicationRecord belongs_to :comment end class Event < ApplicationRecord belongs_to :comment end

Solution

  1. Step 1: Identify polymorphic association pattern

    Comments belong to a polymorphic commentable interface, allowing multiple models to share comments.
  2. Step 2: Match correct model declarations

    class Comment < ApplicationRecord belongs_to :commentable, polymorphic: true end class Article < ApplicationRecord has_many :comments, as: :commentable end class Event < ApplicationRecord has_many :comments, as: :commentable end correctly uses belongs_to :commentable, polymorphic: true in Comment and has_many :comments, as: :commentable in Article and Event.
  3. Final Answer:

    polymorphic belongs_to and has_many as: :commentable -> Option B
  4. Quick Check:

    Polymorphic belongs_to + has_many as: = class Comment < ApplicationRecord belongs_to :commentable, polymorphic: true end class Article < ApplicationRecord has_many :comments, as: :commentable end class Event < ApplicationRecord has_many :comments, as: :commentable end [OK]
Hint: Use belongs_to polymorphic in child, has_many as: in parents [OK]
Common Mistakes:
  • Trying to belongs_to both models separately
  • Using has_many in Comment instead of belongs_to
  • Assigning belongs_to comment in parent models
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard