1
我有以下型号:贪婪加载多态关联
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
,但我得到了同样的错误。
尝试'Conversation.preload ...'? –
是的,给出了同样的错误。 –