Polymorphic association is little tricky to understand among all the rails association. Using this association one model can have belongs_to association with more than one model in a single line of association. As for example in a social networking site there can be comments for a post , uploaded image of the user. So here we can have polymorphic association among these three models Post,Image, and comments.
class Comment < ActiveRecord::Base
belongs_to :commentable, :polymorphic => true
end
class Image < ActiveRecord::Base
has_many :comments, :as => :commentable
end
class Post < ActiveRecord::Base
has_many :comments, :as => :commentable
end
The migration file of comment model:
class CreateComments < ActiveRecord::Migration
def change
create_table :comments do |t|
t.string :comment
t.integer :commentable_id
t.string :commentable_type
t.timestamps
end
end
end
We can also write the above migration as:
class CreateComments < ActiveRecord::Migration
def change
create_table :comments do |t|
t.string :comment
t.references :commentable, :polymorphic => true
t.timestamps
end
end
end
In the commentable_id primary key of Post and Image record will be saved and in commentable_type column 'Image' and 'Post' string will be saved.
We can get the comments in this way:
@image = Image.first
@image_comments = @image.comments
@post = Post.first
@post_comments = @post.comments
0 Comment(s)