3

I'm trying to eager load a polymorphic association while also paginating using the Kaminari gem:

@news_items = NewsItem.includes(:news_source).not_outdated
.where(:group_id => group_ids).order("created_at DESC").page(params[:page]).per(10)

I'm getting the error message:

ActiveRecord::EagerLoadPolymorphicError in Pages#dashboard

Showing 'BLAH BLAH'/dashboard.html.erb where line #49 raised: Can not eagerly load the polymorphic association :news_source

When I remove the Kaminari scope ( .page[:page]).per(10) ), then the error disappears.

Anyone have any ideas? This article suggests that eager loading with polymorphic associations is supported, but only if the conditions/order that might be applied to the Relation as a scope don't reference any other tables (if they do, then Rails uses the LEFT OUTER JOIN method for the eager loading which can't work on polymorphic associations). So: does Kaminari reference another table?

Would appreciate any advice!

Cheers.

Rob d'Apice
  • 2,416
  • 1
  • 19
  • 29

1 Answers1

0

You should always use preload for polymorphic associations.

This error can happen because includes decides to call eager_load if it needs to query conditions on the association, and polymorphic associations are only supported by preload. It's in the documentation

Marian Nasry
  • 821
  • 9
  • 22
seanmorton
  • 371
  • 2
  • 2