Reputation: 17160
I have a Comments model, and I also have a Video, and Photo model. Now, I want for my Video and Photo models to have_many
comments, but that means my Comment model will have to have a belongs to :video
and a belongs_to :model
(as well as foreign keys for each model in the database). Now say I create a Post model in that same application and I want it to have many comments, that would mean I would have to add belongs_to :post
to my Comment class. In rails is there a better way to implement a Comment model when there are many other models that are going to have an association with it, or is this just how it is done? Any advice would be much appreciated.
Upvotes: 1
Views: 316
Reputation: 96944
You're looking for polymorphic associations.
class Comment < ActiveRecord::Base
belongs_to :commentable, :polymorphic => true
end
class Photo < ActiveRecord::Base
has_many :comments, :as => :commentable
end
class Video < ActiveRecord::Base
has_many :comments, :as => :commentable
end
You also have to make some changes to your migrations, see the linked documentation for more information.
Upvotes: 2