【问题标题】:Eager load polymorphic associations急切加载多态关联
【发布时间】:2017-06-07 02:56:57
【问题描述】:

我有以下型号:

class Conversation < ActiveRecord::Base
  belongs_to :sender, foreign_key: :sender_id, polymorphic: true
  belongs_to :receiver, foreign_key: :receiver_id, polymorphic: true

.

class Owner < ActiveRecord::Base

.

class Provider < ActiveRecord::Base

.

class Account < ActiveRecord::Base
  has_one :provider, dependent: :destroy
  has_many :owners, dependent: :destroy

所以在对话中,sender 可以是所有者或提供者。考虑到这一点,我可以进行如下查询:

Conversation.includes(sender: :account).limit 5

这按预期工作。问题是当我想在关联模型帐户中使用 where 子句时。我想过滤关联帐户所在国家/地区为“美国”的对话。像这样的:

Conversation.includes(sender: :account).where('accounts.country' => 'US').limit 5

但这不起作用,我收到错误ActiveRecord::EagerLoadPolymorphicError: Cannot eagerly load the polymorphic association :sender

进行这种查询的正确方法是什么?

我也尝试过使用joins,但我得到了同样的错误。

【问题讨论】:

  • 试过Conversation.preload...?
  • 是的,同样的错误。

标签: ruby-on-rails ruby-on-rails-4 activerecord


【解决方案1】:

我找到了自己的解决方案,以防其他人感兴趣。我最终将joins 与 SQL 查询一起使用:

Conversation.joins("LEFT JOIN owners ON owners.id = conversations.sender_id AND conversations.sender_type = 'Owner'
                  LEFT JOIN providers ON providers.id = conversations.sender_id AND conversations.sender_type = 'Provider'
                  LEFT JOIN accounts ON accounts.id = owners.account_id OR accounts.id = providers.account_id").
                where('accounts.country' => 'US').limit 5

【讨论】:

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