3

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
Jeremy Lynch
  • 6,780
  • 3
  • 52
  • 63
  • Possible duplicate of https://stackoverflow.com/questions/16123492/eager-load-polymorphic – John Hayes-Reed Jul 21 '17 at 02:26
  • Not the same as that question. This question wants ALL comments, that question wants only comments for one class (eg. comments for Post only) – Jeremy Lynch Jul 21 '17 at 02:29
  • I haven't used polymorphic associations for more than 5 years now because they have problems like this. Also they are terrible for data integrity because they are difficult to constrain. – Wizard of Ogz Jul 21 '17 at 02:54

1 Answers1

0
Comment.where(commentable: @user.posts).or(Comment.where(commentable: @user.groups))
Jeremy Lynch
  • 6,780
  • 3
  • 52
  • 63