简体   繁体   English

rails加入多态关联

[英]rails joins polymorphic association

I have a ploymorphic association named Notifiable in a model named Notifiaction : 我在名为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

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 当我尝试加入通知时通知( Notification.joins{notifiable} notifiable Notification.joins{notifiable} - 它的吱吱声,活动记录代码会有相同的结果)我得到错误: 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 我错过了什么

You can eager load both polymorphic associations by using includes: 您可以通过使用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. 考虑Bill和Balance结果与查询结果匹配,include应该在查询结果中预加载两个模型。 ie: 即:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM