Rails Polymorphic Associations
What is a polymorphic association?
A polymorphic association is a relationship between one object and another object where the other object can be of any type. These are useful when dealing with similar relationships between a object and many others. For example in Facebook you can make requests, game requests, friendship requests, event requests, etc. I would guess they have a request object which has a polymorphic relationship to either a game (app) object, friendship object or event object. This way you have one list of requests, but many different types in that list.
How does it work?
Rails stores an id and a type. So If I had in my migration
t.references :entity, :polymorphic => true
The following line describes the polymorphic relationship and in the model creates a entity_id and a entity_type.
So now when you can do the following
#later in code you could
request = Request.create(:entity => Email.last)
#when you then do the following
#you get an array of all of them, User’s and Emails, and any other model you see fit to pop into it.
In: Uncategorized · Tagged with: Polymorphic Associations, Rails