【问题标题】:Active Record eagerly load polymorphic associationActive Record 急切地加载多态关联
【发布时间】:2018-01-12 14:05:30
【问题描述】:

我有以下型号:

class User < ApplicationRecord
  has_one :card, as: :cardable
  scope :active, -> { where(active: true) }
end

class Organisation < ApplicationRecord
  has_one :card, as: :cardable
  scope :active, -> { where(active: true) }
end

class Card < ApplicationRecord
  belongs_to :cardable, polymorphic: true
end

我想查找关联用户或组织处于活动状态的所有卡片。

我认为以下方法会起作用:

Card.includes(:cardable).where(cardable: {active: true})

但这会引发错误:

ActiveRecord::EagerLoadPolymorphicError: Cannot eagerly load the polymorphic association :cardable

我正在尝试使用 ActiveRecord 做的事情是否可行? 我用similar title 查看了其他问题,但我不确定这些场景是否与这个场景足够相似。

【问题讨论】:

  • 从the accepted answer 到您链接的the question,您是否尝试在Card 中为:user 和:organization 使用belongs to 下的belongs to 声明?抱歉,没有时间为自己设置和测试一个工作示例。

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


【解决方案1】:

我认为这应该可行:

cardable_ids = User.active.pluck(:id) + Organisation.active.pluck(:id)
Card.where(cardable_id: cardable_ids)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-16
    • 1970-01-01
    • 2017-12-26
    • 2010-12-01
    • 2017-08-28
    相关资源
    最近更新 更多