2017-06-07 88 views
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,但我得到了同樣的錯誤。

+0

嘗試'Conversation.preload ...'? –

+0

是的,給出了同樣的錯誤。 –

回答

1

我發現自己是一個解決方案,以防其他人感興趣。我結束了使用SQL查詢使用joins

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