扶手:实现一个可重复使用的评价模型 [英] Rails: Implementing a reuseable Comment model

查看:98
本文介绍了扶手:实现一个可重复使用的评价模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个评论的模式,我也有一个视频和照片模式。现在,我要为我的视频和照片模式,以 have_many 的意见,但是这意味着我的评价模型必须有一个属于:视频 belongs_to的:模型(以及为数据库中的每个模型的外键)。现在,说我创建一个Post模型在同一应用程序,我希望它有很多评论,这将意味着我将不得不增加 belongs_to的:交来我的评论类。在轨是否有更好的方法来实现评价模型时,还有许多其他的模式,将会有关联的,或者是这一点,仅仅是如何做的?任何意见将是多少AP preciated。

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.

推荐答案

您正在寻找的多态关联的。

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.

这篇关于扶手:实现一个可重复使用的评价模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆