Polymorphic Associations

Z. Michael Luo
Aug 22, 2017 · 2 min read

One of the more interesting offerings Active Record and Rails has on associations between tables is something called the Polymorphic Association. A polymorphic association is basically an association in which one model can ‘belong to’ two or more other models. So say if you have picture model that can either belong to an employee model or a product model, it can be done using active record polymorphic associations.

Active Record executes this association through a polymorphic belongs_to relationship. One can think of this declaration as an interface that any other model can use.

The migration can be simplified by using ‘t.references’.

Although this association isn’t the most commonly used, It’s still a very useful and very simple potential solution to have under your belt.

)

Musician & Programmer

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade