ben*_*ams 7 activerecord join ruby-on-rails polymorphic-associations
我在名为Notifiable的模型中命名了一个ploymorphic关联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
Run Code Online (Sandbox Code Playgroud)
当我尝试加入通知时通知(Notification.joins{notifiable}- 它是吱吱声,活动记录代码会有相同的结果)我得到错误:ActiveRecord::EagerLoadPolymorphicError: Can not eagerly load the polymorphic association :notifiable
我已经看过一些有关此异常的帖子,但当我尝试加入表格时,它们都不是我的情况.可能吗?我错过了什么
您可以使用 include 预先加载这两个多态关联:
Notification.where(whatever: "condition").includes(:notifiable)
Run Code Online (Sandbox Code Playgroud)
考虑到账单和余额结果都与查询结果匹配,包含应在查询结果中预加载这两个模型。IE:
Notification.where(whatever: "condition").includes(:notifiable).map(&:notifiable)
# => [Bill, Balance, etc]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12878 次 |
| 最近记录: |