Explain a polymorphic association?
Explain a polymorphic association?
Polymorphic associations allow a model to belong to more than one other model through a single association.
RoR QA polymorphic1
A polymorphic association schematic, from Rubyonrails.org
RoR QQ polymorphic2
Model structures of a polymorphic association, in Ruby code, from Ruybonrails.org
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.)
Comments
Post a Comment