Polymorphic Associations in Ruby on Rails

You might have instances where the associations could be with multiple models. For example, if you have a Picture model that can be associated with either a Student model or an Employee model. In this case, you really want to be able to call @picture.imageable to get the image. This is where polymorphic associations come in.

class Picture < ActiveRecord::Base
  belongs_to :imageable, :polymorphic => true
end

class Student < ActiveRecord::Base
  has_many :pictures, :as => :imageable
end

class Employee < ActiveRecord::Base
  has_many :pictures, :as => :imageable
end

You can think of a polymorphic belongs_to declaration as setting up an interface that any other model can use.
You can also retrieve a collection of pictures: @student.pictures or @employee.pictures from instances of Student or Employee model.

To make this work, you need to declare both a foreign key column and a type column in the model that declares the polymorphic interface:

class CreatePictures < ActiveRecord::Migration
  def self.up
    create_table :pictures do |t|
      t.string  :name
      t.integer :imageable_id
      t.string  :imageable_type
      t.timestamps
    end
  end

  def self.down
    drop_table :pictures
  end
end

Finally, you can read more on the documentation written by Rails team.

No comments as yet.

Anonymous - Gravatar

No comments have yet been made to this posting.

Commentors on this Post-

Leave a Comment-

Comment Guidelines: Basic XHTML is allowed (a href, strong, em, code). All line breaks and paragraphs are automatically generated. Off-topic or inappropriate comments will be edited or deleted. Email addresses will never be published. Keep it PG-13 people!

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>

All fields marked with "*" are required.