Rails: Implementing a reuseable Comment model

岁酱吖の 提交于 2019-12-08 03:20:34

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/5138065/rails-implementing-a-reuseable-comment-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!