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 | |
| end | |
| class Event < ActiveRecord::Base | |
| attr_accessible :name, :organizer, :place | |
| has_many :comments, :as => :commendable | |
| end | |
| class Comment < ActiveRecord::Base | |
| attr_accessible :comment | |
| belongs_to :commendable, :polymorphic => true | |
| end | |
| # Migration: create_comments.rb | |
| class CreateComments < ActiveRecord::Migration | |
| def change | |
| create_table :comments do |t| | |
| t.text :comment | |
| t.references :commendable, :polymorphic => true | |
| t.timestamps | |
| end | |
| end | |
| end |
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:
- Demo: Live Demo can be viewed from my Heroku App. Please click on the link: http://blooming-peak-9982.herokuapp.com/users

Leave a Reply