渴望加载多态关联

时间:2017-06-07 02:56:58

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

我有以下型号:

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

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

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

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

进行此类查询的正确方法是什么?

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

1 个答案:

答案 0 :(得分: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