rails加入多态关联

我在名为Notifiaction的模型中有一个名为Notifiable的ploymorphic关联:

 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  true belongs_to :bill, foreign_key: 'notifiable_id', conditions: "notifiable_type = 'Bill'" belongs_to :balance, foreign_key: 'notifiable_id', conditions: "notifiable_type = 'Balance'" end 

当我尝试加入通知时通知( Notification.joins{notifiable} notifiable Notification.joins{notifiable} – 它是吱吱声,活动记录代码会有相同的结果)我得到错误: ActiveRecord::EagerLoadPolymorphicError: Can not eagerly load the polymorphic association :notifiable

我已经看过一些有关此exception的post,但当我尝试加入表格时,它们都不是我的情况。 可能吗? 我错过了什么

您可以通过使用includes来急切加载两个多态关联:

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

考虑Bill和Balance结果与查询结果匹配,include应该在查询结果中预加载两个模型。 即:

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

由于您已经声明了帐单和余额关联,因此您可以加入单个关联并对其进行联盟。

就像是

 scope :billiables_for_account, ->(account) do union_scope(joins(:bill).where(bills: {account: account}), joins(:balance).where(bills: {account: account})) end