rails:自我引用关联

我的需求非常简单:我有一个Tip表来接收评论并有评论也可以收到评论。

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

我试图通过使用自我引用关联使用一个注释表。 有些资源似乎会带来不止一张表,这与我的需求不同。 所以我想出了以下建模评论:

class Comment  :inverse_comments, :source => :comment end 

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

我需要做些什么改变才能使模型有效?

谢谢。

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

为此,您需要在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