Prepare Interview

Mock Exams

Make Homepage

Bookmark this page

Subscribe Email Address

Ruby%20On%20Rails%20Interview%20Questions%20and%20Answers

Question: Explain a polymorphic association in Ruby on Rails.
Answer: Polymorphic associations allow a model to belong to more than one other model through a single association.

class Picture < ActiveRecord::Base
  belongs_to : imageable, polymorphic: true
end

class Employee < ActiveRecord::Base
  has_many : pictures, as: : imageable
end

class Product < ActiveRecord::Base
  has_many : pictures, as: : imageable
end
  • Here, the class Picture belongs_to both Employee and Product, but does so through a single association rather than through multiple.
  • Be sure to know an appropriate situation to create a polymorphic association, such as creating a comment model associated with multiple other models (articles, photos, etc.). The advantage of using polymorphism here is that it allows you to create a single comment model, rather than separate models for each one (PhotoComment model, ArticleComment model, etc.)
Is it helpful? Yes No

Most helpful rated by users:

©2024 WithoutBook