rails加入多态关联

时间:2014-08-19 18:21:49

标签: ruby-on-rails activerecord join polymorphic-associations

我在名为Notifiable的模型中有一个名为Notifiaction的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} - 它的吱吱声,活动记录代码会产生相同的结果)我收到错误:ActiveRecord::EagerLoadPolymorphicError: Can not eagerly load the polymorphic association :notifiable

我已经看过一些有关此异常的帖子,但当我尝试加入表格时,这些都不是我的情况。可能吗?我错过了什么

2 个答案:

答案 0 :(得分:2)

您可以使用includes:

来加载两种多态关联
Notification.where(whatever: "condition").includes(:notifiable)

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

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

答案 1 :(得分:0)

由于您已经宣布了账单和余额关联,您可以加入个人关联并对其进行联盟。

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