views:

30

answers:

2

Say I have a bunch of Models, Articles, Downloads, Videos, Pictures, I want to be able to have comments on all these models with a single Comment model so I can track comments made by a certain user across all these models. What's the best way to go about this?

A: 

This is exactly what polymorphic associations were designed for.

Check http://guides.rails.info/association_basics.html#polymorphic-associations

Basically you would do something like this:

Class User < ActiveRecord::Base
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :commentable, :polymorphic => true
  belongs_to :user
end

class Video < ActiveRecord::Base
  has_many :comments, :as => :commentable
end
class Article < ActiveRecord::Base
  has_many :comments, :as => :commentable
end
# ... so on

Check the link above for how to design your migration. You want commentable_id and commentable_type columns, instead of the imageable_* ones they use in the example.

rspeicher
A: 

After looking around a bit, I found this screencast to be very helpful as well, if anyone else is also looking.

Randuin