2010-10-14 62 views
3

例如我有一个评论模型,我有一个帖子模型,但评论可以评论其他评论。所有连接表都有表吗?

所以看来我需要一个连接表,我会打电话给commentables。要创建这个,我真的需要创建一个带有post_id和comment_id的可评论表吗?

或者,我可以做这样的事情没有一个:

has_many   :comments, 
        :through => :commentables, 
        :source => :post 

不是真的知道什么是做到这一点的最好办法。我是一个巨大的新手。

回答

5

不,你不应该在这种情况下需要一个连接表。连接表是针对has_and_belongs_to_many的关系,在这种情况下,您不需要拥有其中的一个(注释不能属于许多帖子,可以吗?)。

你有两个选择来解决这个问题。首先是建立一个多态的关系:

class Post < ActiveRecord::Base 
    has_many :comments, :as => :parent 
end 

class Comment < ActiveRecord::Base 
    belongs_to :parent, :polymorphic => true 
    has_many :children, :class_name => 'Comment', :as => :parent # We need to point this relationship to the Comment model, otherwise Rails will look for a 'Child' model 
end 

这将允许评论要么属于一个帖子,或其他评论。 Comment.last.parent将返回PostComment记录。

第二个选择是让所有的意见都属于一个特定的职位,但有自己的亲子关系:

class Post < ActiveRecord::Base 
    has_many :comments 
end 

class Comment < ActiveRecord::Base 
    belongs_to :post 
    belongs_to :parent, :class_name => 'Comment' # We need to point this relationship to the Comment model, otherwise Rails will look for a 'Parent' model 
    has_many :children, :class_name => 'Comment' # We need to point this relationship to the Comment model, otherwise Rails will look for a 'Child' model 
end 

这样一来,您的意见将永远属于一个帖子,还有可能属于另一个评论。

如果你打算嵌套评论(至少多于一个级别),我会建议第二个选项。这将允许您在一个查询中获取特定帖子的所有评论(而不必为每条评论查找子文件),并且可以在渲染它们之前对应用程序中的评论进行排序。但无论哪种方式应该工作。

+3

很棒的回答。 +1 – 2010-10-14 02:20:14

+0

哇!我无法为此感谢你!非常感谢你 – Trip 2010-10-14 10:15:48

+0

不客气。 :) – vonconrad 2010-10-15 02:08:46

相关问题