我通过多态关联在应用程序中使用acts_as_commentable,并希望允许对注释进行线程化。我已经完成了这项工作,但现在我想创建一个返回树状结构并避免N+1查询问题的index操作。我有:
item.comments.includes(:comments)但是,它运行以下查询,该查询不执行任何紧急加载:
SELECT "comments".* FROM "comments" WHERE ("comments".commentable_id = 22 AND "comments".commentable_type = 'Item')有没有办法让它在自引用多态关联上运行?
发布于 2011-07-19 19:31:57
如果在Comment中有两个belongs_to关联,而不是让注释本身成为可注释的,您可能会更容易一些。一个用于原始注释,另一个用于线程中的父注释。
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
…
endhttps://stackoverflow.com/questions/6701619
复制相似问题