3
votes

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.

1
Can you edit your post and add the models?fro_oo
Or maybe something like: Kaminari.paginate_array(@ news_items.all).page(params[:page]).per(10)fro_oo
This question is more than 6 months on, and I think my code has well and truly moved on. Will try to have a peek back at it later today.Rob d'Apice
did you try add includes(:news_source) to the end of you expression?Fivell

1 Answers

0
votes

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