簡體   English   中英

rails加入多態關聯

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM