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

create_table :request do |t|
t.integer    :user_id
t.integer    :requested_id
t.integer    :status
t.boolean    :viewed
t.text       :description

t.references :entity, :polymorphic => true

The following line describes the polymorphic relationship and in the model creates a entity_id and a entity_type.

t.references :entity, :polymorphic => true

So now when you can do the following

request = Request.create(:entity => current_user)
#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.

Posted on May 28, 2009 at 10:06 pm by Jordan Carter · Permalink
In: Uncategorized · Tagged with: ,

One Response

  1. Written by Luis Lavena
    on May 29, 2009 at 12:31 am

    Nice post, but you missed the @[email protected] part when calling references.

    Without it, it just implies a belongs_to association.

    More docs:



Leave a Reply