[英]rails joins polymorphic association
我在名为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 < 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
当我尝试加入通知时通知( Notification.joins{notifiable}
notifiable Notification.joins{notifiable}
- 它的吱吱声,活动记录代码会有相同的结果)我得到错误: ActiveRecord::EagerLoadPolymorphicError: Can not eagerly load the polymorphic association :notifiable
我已经看过一些有关此异常的帖子,但当我尝试加入表格时,它们都不是我的情况。 可能吗? 我错过了什么
您可以通过使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.