ActiveRecord::EagerLoadPolymorphicError: Cannot eagerly load the polymorphic association

 

If you have encountered this error and wondering how to fix it this post is for you.

Rails raises this error when it tries to eager load a polymorphic association using a JOIN.

For example i have a Booking which belongs_to polymorphic association order. An Order can be a PickupOrder or DeliveryOrder

class Booking < ApplicationRecord
  belongs_to :order, polymorphic: true
end
class PickupOrder < ApplicationRecord
  has_many :bookings, as: :order, dependent: :destroy, inverse_of: :order
end
class DeliveryOrder < ApplicationRecord
  has_many :bookings, as: :order, dependent: :destroy, inverse_of: :order
end

I can load all bookings along with orders like this

Booking.includes(:order)

Now if I want to search list of bookings by `order_name` like `ja`

Booking.includes(:order).references(:order).where("order.order_name ilike %ja%")

Throws the error

​​ActiveRecord::EagerLoadPolymorphicError: Cannot eagerly load the polymorphic association :order

Solution: Do it in sql. with left outer joins.

Booking.joins("left outer join delivery_orders on delivery_orders.id = bookings.order_id and bookings.order_type='DeliveryOrder'").
        joins("left outer join pickup_orders on pickup_orders.id = bookings.order_id and bookings.order_type='PickupOrder'").
        where("pickup_orders.order_name like '%ja%' or delivery_orders.order_name like '%ja%'")

Happy coding!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.