4

I'm trying to eager load a nested polymorphic association. I can't seem to find a solution.

Here is my model setup:

class Post
  has_many :comments
end

class Comment
  belongs_to :ownable, polymorphic: true
end

class User
  has_many :comments, as: :ownable
end

And here is what I'm trying to do:

Post.includes(comments: :ownable).to_a

But it's throwing this error:

ActiveRecord::EagerLoadPolymorphicError - Can not eagerly load the polymorphic association :ownable

How can I do eager load this nested polymorphic association?

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
axsuul
  • 7,370
  • 9
  • 54
  • 71
  • possible duplicate of [Eager load polymorphic](http://stackoverflow.com/questions/16123492/eager-load-polymorphic) – Makoto May 12 '15 at 20:39

1 Answers1

2

First of all your post has_many comments should also be set :as => ownable

    class Post
      has_many :comments, as: :ownable
    end

Be even after changing this, you'll still get the same error since rails cannot find a table ownable.

There is a work around posted here Eager load polymorphic

Community
  • 1
  • 1
Steve007
  • 241
  • 1
  • 3
  • 11