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

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}-这很奇怪, Activity 记录代码将具有相同的结果)时,出现错误:ActiveRecord::EagerLoadPolymorphicError: Can not eagerly load the polymorphic association :notifiable
我已经看到了一些有关此异常的帖子,但是当我尝试仅加入表时,这些帖子都不是我的情况。可能吗?我在想什么

最佳答案

您可以通过使用include来渴望加载两个多态关联:

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

考虑到“帐单”和“余额”结果均与查询结果相匹配,包含应在查询结果中预加载两个模型。 IE:
Notification.where(whatever: "condition").includes(:notifiable).map(&:notifiable)
# => [Bill, Balance, etc]

关于ruby-on-rails - Rails加入多态关联,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25390384/

10-11 17:57