Rails:自我参照关联

发布于 2024-09-05 18:54:37 字数 466 浏览 3 评论 0原文

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

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

我尝试通过自引用关联来使用一个评论表。有些资源似乎将不止一张表带入其中,这与我的需求不同。所以我想出了以下模型以供评论:

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

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

我需要做哪些改变才能使模型发挥作用?

谢谢。

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

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?

thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

半城柳色半声笛 2024-09-12 18:54:37

我相信您应该使用多态关联

为此,您需要在 comments 表中添加 commentable_idcommentable_type。你的模型应该看起来像:

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

I believe you should use a polymorphic association.

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

This way you can use

@tip.comments
@comment.comments
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文