Bird
Raised Fist0
Ruby on Railsframework~20 mins

Polymorphic associations in Ruby on Rails - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Polymorphic Pro
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
How does polymorphic association behave in Rails?

Given a polymorphic association where Comment belongs to commentable which can be either Post or Image, what will comment.commentable return if the comment belongs to a post?

Ruby on Rails
class Comment < ApplicationRecord
  belongs_to :commentable, polymorphic: true
end

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

post = Post.create(title: "Hello")
comment = Comment.create(body: "Nice post!", commentable: post)

result = comment.commentable
AThe Post object associated with the comment
BThe Comment object itself
CAn array of all comments for the post
DA string with the post's title
Attempts:
2 left
💡 Hint

Think about what belongs_to :commentable means in Rails.

📝 Syntax
intermediate
2:00remaining
Identify the correct polymorphic association syntax

Which option correctly defines a polymorphic association in Rails?

A
class Picture &lt; ApplicationRecord
  belongs_to :imageable
end
B
class Picture &lt; ApplicationRecord
  has_many :imageable, polymorphic: true
end
C
class Picture &lt; ApplicationRecord
  belongs_to :imageable, polymorphic: true
end
D
class Picture &lt; ApplicationRecord
  has_one :imageable, polymorphic: true
end
Attempts:
2 left
💡 Hint

Remember that the model holding the foreign key uses belongs_to with polymorphic: true.

🔧 Debug
advanced
2:00remaining
Why does this polymorphic association raise an error?

Given the following code, why does comment.commentable raise ActiveRecord::RecordNotFound?

Ruby on Rails
class Comment < ApplicationRecord
  belongs_to :commentable, polymorphic: true
end

comment = Comment.create(body: "Test", commentable_type: "Post", commentable_id: 9999)
comment.commentable
ABecause belongs_to requires inverse_of option for polymorphic
BBecause there is no Post record with id 9999 in the database
CBecause commentable_type should be lowercase 'post'
DBecause the polymorphic association is missing the :dependent option
Attempts:
2 left
💡 Hint

Check if the associated record exists in the database.

❓ state_output
advanced
2:00remaining
What is the count of comments for a polymorphic association?

Given a Post with 3 comments and an Image with 2 comments, what is the output of Comment.where(commentable_type: 'Post').count?

Ruby on Rails
post = Post.create(title: "Post")
image = Image.create(name: "Image")
3.times { Comment.create(body: "Post comment", commentable: post) }
2.times { Comment.create(body: "Image comment", commentable: image) }

result = Comment.where(commentable_type: 'Post').count
A3
B5
C2
D0
Attempts:
2 left
💡 Hint

Filter comments by the commentable_type column.

🧠 Conceptual
expert
2:00remaining
Why use polymorphic associations in Rails?

Which is the best explanation for why polymorphic associations are useful in Rails?

AThey replace the need for join tables in many-to-many relationships
BThey enforce strict foreign key constraints between models
CThey automatically generate database indexes for faster queries
DThey allow a model to belong to more than one other model on a single association
Attempts:
2 left
💡 Hint

Think about how one model can be linked to different models using the same association.

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