Eager load (includes) polymorphic association

Viewed 1441

Consider the following polymorphic relationship:

class Comment
  belongs_to :commentable, polymorphic: true
end

class User
  has_many :posts
  has_many :groups
end

class Group
  belongs_to :user
  has_many :comments, as: :commentable
end

class Post
  belongs_to :user
  has_many :comments, as: :commentable
end

Essentially a user has post comments and group comments. I want to return user total comments. One way of achieving this is:

posts = @user.posts.map {|c| c.comments}.flatten
groups = @user.groups.map {|c| c.comments}.flatten

However, this is database intensive. It is possible to eager load here like this:

Comment.includes(:commentable).where(commentable: {user_id: self.id})
# ActiveRecord::EagerLoadPolymorphicError: Cannot eagerly load the polymorphic association :commentable
1 Answers
Related