Rails:自我参照关联
我的需求很简单:我有一个提示表来接收评论,也有评论来接收评论。
为了检索存储在同一个表(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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我相信您应该使用多态关联。
为此,您需要在
comments
表中添加commentable_id
和commentable_type
。你的模型应该看起来像:这样你就可以使用
I believe you should use a polymorphic association.
For that you'll need to add a
commentable_id
and acommentable_type
on yourcomments
table. And your models should look like:This way you can use