渴望加载自我引用多态关联

时间:2011-07-15 00:46:34

标签: ruby-on-rails ruby

我通过多态关联在应用程序中使用acts_as_commentable,并希望允许对注释进行线程化。我有这个工作,但现在我想创建一个index动作,它将返回树状结构并避免N + 1查询问题。我有:

item.comments.includes(:comments)

但是,它会运行以下查询,该查询不会执行任何预先加载:

SELECT "comments".* FROM "comments" WHERE ("comments".commentable_id = 22 AND "comments".commentable_type = 'Item')

有什么方法可以让它在自引用多态关联上运行?

1 个答案:

答案 0 :(得分:3)

如果您在belongs_to中有两个Comment关联,那么您可以更轻松地自行评论评论。一个用于原始注释,另一个用于线程中的父注释。

class Comment < ActiveRecord::Base
  belongs_to :commentable, polymorphic: true
  belongs_to :parent, class_name: Comment
  has_many :replies, class_name: Comment, inverse_of: :parent, include: :replies
  …
end