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.integer :user_id
t.integer :requested_id
t.integer :status
t.boolean :viewed
t.text :description
t.references :entity, :polymorphic => true
t.timestamps
end
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
Request.all
#you get an array of all of them, User’s and Emails, and any other model you see fit to pop into it.
Related Posts
In: Uncategorized · Tagged with: Polymorphic Associations, Rails
on May 29, 2009 at 12:31 am
Permalink
Nice post, but you missed the @[email protected] part when calling references.
Without it, it just implies a belongs_to association.
More docs:
http://apidock.com/rails/ActiveRecord/ConnectionAdapters/TableDefinition/column
HTH.