Rails 3: Polymorphic Associations in Action

Hi Folks,

In this short article, I would like to brief about “Rails polymorphic associations“. Below are the high-level pointers.

  • What is Polymorphic Association
  • How Rails handles it
  • Example explained
  • Demo

So, Let’s start:

  • What is Polymorphic Association: In OOP, Polymorphic means “of-many“.

There is a well documented and well explained Railscasts for this. Refer to this link for more information: http://railscasts.com/episodes/154-polymorphic-association

  • Example Explained:

class User < ActiveRecord::Base
attr_accessible :email, :name
has_many :comments, :as => :commendable
class Event < ActiveRecord::Base
attr_accessible :name, :organizer, :place
has_many :comments, :as => :commendable
class Comment < ActiveRecord::Base
attr_accessible :comment
belongs_to :commendable, :polymorphic => true
# Migration: create_comments.rb
class CreateComments < ActiveRecord::Migration
def change
create_table :comments do |t|
t.text :comment
t.references :commendable, :polymorphic => true

view raw


hosted with ❤ by GitHub

Code snippet can be downloaded from Github. The path for the same is: git@github.com:puneetpandey/rails3_singleTableInheritance.git

Once set-up. Type the URL’s below:

  1. http://localhost:3000/events
  2. http://localhost:3000/users

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s