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
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
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%'")