不,在这种情况下您不需要连接表。联接表用于has_and_belongs_to_many 关系,在这种情况下,您不需要其中之一(cmets 不能属于许多帖子,对吗?)。
您有两种选择。首先是创建多态关系:
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 将返回 Post 或 Comment 记录。
第二种选择是让所有的cmet都属于一个特定的帖子,但是有自己的父子关系:
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
这样,您的 cmets 将始终属于某个帖子,并且有可能属于另一个评论。
如果您打算嵌套 cmets(至少不止一层),我建议您使用第二个选项。这将允许您在一个查询中获取特定帖子的所有 cmets(而不必为每个评论查找子项),并且您可以在呈现之前对应用程序中的 cmets 进行排序。但无论哪种方式都应该有效。