💎 Ruby on Rails
Beginner
What is polymorphic association in Rails?
Answer
A polymorphic association allows a model to belong to more than one other model type through a single association. Example: a Comment model can belong to both Post and Video. The comments table has two columns: commentable_id (integer) and commentable_type (string, stores the class name like "Post" or "Video"). Declare in the model: belongs_to :commentable, polymorphic: true. In Post: has_many :comments, as: :commentable. Polymorphic associations keep your schema DRY when multiple models share the same associated behavior.
Previous
What is the Rails request-response lifecycle?
Next
What is the N+1 query problem and how do you fix it?