Rails connect with polymorphic association

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 a notification with a notification ( Notification.joins{notifiable} is squeel, the active recording code will have the same result) I get an error: ActiveRecord::EagerLoadPolymorphicError: Can not eagerly load the polymorphic association :notifiable

I saw several posts about this exception, but none of them was exactly my case when I try to just join tables. Is it possible? what am i missing

+7
join ruby-on-rails activerecord polymorphic-associations
source share
2 answers

You can load both polymorphic associations using:

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

Given that the results of both Bill and Balance correspond to the query result, include must first load both models into the query result. i.e:

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

Since you already have announced accounts and balance associations, you can join individual associations and make an alliance 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 
0
source share

All Articles