Best way to approach a Model belonging to one of many possible models
Say I have a bunch of Mo开发者_StackOverflowdels, 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?
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.
精彩评论