gpt4 book ai didi

ruby-on-rails - rails 加入多态关联

转载 作者:行者123 更新时间:2023-12-04 05:48:22 26 4
gpt4 key购买 nike

我有一个名为 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} - 它是尖叫声,事件记录代码将具有相同的结果)加入通知时,我收到错误: ActiveRecord::EagerLoadPolymorphicError: Can not eagerly load the polymorphic association :notifiable
我看过一些关于这个异常(exception)的帖子,但是当我尝试加入表格时,没有一个是我的情况。是否可以?我错过了什么

最佳答案

您可以使用包含来预先加载两个多态关联:

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

考虑到 Bill 和 Balance 结果都匹配查询结果,include 应该在查询结果中预加载这两个模型。 IE:
Notification.where(whatever: "condition").includes(:notifiable).map(&:notifiable)
# => [Bill, Balance, etc]

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com