rails:自我参照协会 [英] rails: self-referential association

查看:38
本文介绍了rails:自我参照协会的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的需求很简单:我有一个提示表来接收评论,也有评论来接收评论.

My needs are very simple: I have a Tip table to receive comments and have comments to receive comments, too.

为了检索存储在同一个表(comments)中的每条评论,我为评论的评论创建了另一个键:inverse_comments".

To retrieve each comment that is stored in the same table (comments), I created another key for the comments on comments: "inverse_comments".

我尝试通过使用自引用关联来使用一个评论表.一些资源似乎带来了不止一张桌子,这与我的需求不同.所以我想出了以下建模以供评论:

I tried to use one comments table by using self-referntial association. Some resources seem to bring more than one table into the piture which are diffent from my needs. So I came up whth the following modeling for comments:

class Comment < ActiveRecord::Base
  belongs_to :tip 
  belongs_to :user
  has_many :mycomments, 
           :through => :inverse_comments,
           :source => :comment
end

显然这里缺少一些东西,但我无法弄清楚.有人可以启发我吗:

Apparently something is missing here but I cannot figure it out. Could some one enlighten me on this:

我需要做哪些更改才能使模型正常工作?

what changes I need to do to make the model work?

谢谢.

推荐答案

我相信你应该使用 多态关联.

I believe you should use a polymorphic association.

为此,您需要在 comments 表中添加 commentable_idcommentable_type.您的模型应如下所示:

For that you'll need to add a commentable_id and a commentable_type on your comments table. And your models should look like:

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

class Tip < ActiveRecord::Base 
   has_many :comments, :as => :commentable
end

这样你就可以使用

@tip.comments
@comment.comments

这篇关于rails:自我参照协会的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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