rails joins polymorphic association

benams picture benams · Aug 19, 2014 · Viewed 13.9k times · Source

I have a ploymorphic association named Notifiable in a model named Notifiaction:

module Notifiable
  def self.included(base)
    base.instance_eval do
      has_many :notifications, :as => :notifiable, :inverse_of => :notifiable, :dependent => :destroy
    end
  end
end

class Bill < ActiveRecord::Base
  include Notifiable
end

class Balance < ActiveRecord::Base
  include Notifiable
end

class Notification
  belongs_to :notifiable, :polymorphic => true
  belongs_to :bill, foreign_key: 'notifiable_id', conditions: "notifiable_type = 'Bill'"
  belongs_to :balance, foreign_key: 'notifiable_id', conditions: "notifiable_type = 'Balance'"
end

when I try to join notification with notifiable (Notification.joins{notifiable} - it's squeel, active record code will have the same result) I get the error: ActiveRecord::EagerLoadPolymorphicError: Can not eagerly load the polymorphic association :notifiable

I've seen some posts about this exception but none of them was exactly my case when I try to just join the tables. Is it possible? what am I missing

Answer

Shai picture Shai · Oct 27, 2014

You can eager load both polymorphic associations by using includes:

Notification.where(whatever: "condition").includes(:notifiable)

Considering both Bill and Balance results match the query result, the include should preload both models in the query result. ie:

Notification.where(whatever: "condition").includes(:notifiable).map(&:notifiable)
# => [Bill, Balance, etc]