开发者

Eager Loading Self Referencing Polymorphic Association

I'm using acts_as_commentable to in an application through a polymorphic association and wanted to allow comments to be threaded. I've got this working, but now I want to create an index a开发者_JS百科ction that will return a tree like structure and avoid the N+1 query issue. I have:

item.comments.includes(:comments)

However, it runs the following query which doesn't do any eager loading:

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

Any way to get this to run on a self referencing polymorphic association?


Instead of making comments commentable themselves, you could have an easier time if you have two belongs_to associations in Comment. One for the original commentable, another for the parent comment in the thread.

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜