Reputation: 4646
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
Upvotes: 7
Views: 14947
Reputation: 155
Since you already have the bill and balance associations declared, you Can join individual associations and Do a Union on them.
Something like
scope :billiables_for_account, ->(account) do
union_scope(joins(:bill).where(bills: {account: account}),
joins(:balance).where(bills: {account: account}))
end
Upvotes: 0
Reputation: 1499
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]
Upvotes: 2