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?
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
Think about what belongs_to :commentable means in Rails.
The commentable method returns the actual object the comment belongs to, which is the Post instance in this case.
Which option correctly defines a polymorphic association in Rails?
Remember that the model holding the foreign key uses belongs_to with polymorphic: true.
The model that stores the polymorphic foreign keys uses belongs_to :association_name, polymorphic: true. Other models use has_many or has_one without polymorphic.
Given the following code, why does comment.commentable raise ActiveRecord::RecordNotFound?
class Comment < ApplicationRecord belongs_to :commentable, polymorphic: true end comment = Comment.create(body: "Test", commentable_type: "Post", commentable_id: 9999) comment.commentable
Check if the associated record exists in the database.
The error occurs because Rails tries to find a Post with id 9999, which does not exist, causing ActiveRecord::RecordNotFound.
Given a Post with 3 comments and an Image with 2 comments, what is the output of Comment.where(commentable_type: 'Post').count?
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
Filter comments by the commentable_type column.
The query counts only comments where commentable_type is 'Post', which are 3.
Which is the best explanation for why polymorphic associations are useful in Rails?
Think about how one model can be linked to different models using the same association.
Polymorphic associations let a model belong to multiple other models through one association, making code simpler and more flexible.