Friday, June 17, 2011

Notes when using Eager Loading on Polymorphic relationship

Eager Loading on Polymorphic calls
After checking the Rails API, it is confirmed that eager loading on polymorphic column works. "Eager loading is supported with polymorphic associations." Rails API

My eager loading is a deep hierarchy of associations (people -> reference -> source). so my scope is something like this:
@people = People.includes([:comments, {:reference => :source}])

Problem 1
However, when I use the @people in the view some of them work as expected but some of them throws EagerLoadPolymorphicError:
ActiveRecord::EagerLoadPolymorphicError: Can not eagerly load the polymorphic association :reference

To solve this, usually a loading trigger before the method call would solve it. For example, calling #first, #last or #any


Problem 2
After finish the each loop on @people in the view, I call a function which is a scoped summation function, e.g. #self.total_membership_fees. And this line throws the EagerLoadPolymorphicError !
the loop works fine but the scoped class function does not.

It is like the @people active record relationship is an immutable object which has to preload in every scope.


To solve this, I could do self.any? before self.sum(&:membership_fee). but I simply use another scoped object for calculating the total, before my total_x method does not requires the polymorphic relationships.


Hope it helps clarifying your problem too.

No comments:

Post a Comment