2016-08-17 98 views
0

我無法從軌道轉換belongs_to的關係與包括 3格式到Rails 4.轉換belongs_to的與包括從導軌3到導軌4

# Rails 3, this works fine. 
class Mobileownerdisclosure < ActiveRecord::Base 
    belongs_to :mobileuser, foreign_key: 'mobileowner_id', conditions: "mobileownerdisclosures.mobileowner_type = 'Mobileuser'", include: :mobileownerdisclosures 
end 

# Rails 4 format that I can not get to work... 
class Mobileownerdisclosure < ActiveRecord::Base 
    belongs_to :mobileuser, -> { where("mobileownerdisclosures.mobileowner_type = 'Mobileuser'").includes(:mobileownerdisclosures) }, foreign_key: 'mobileowner_id' 
end 

.includes(:mobileownerdisclosures )似乎根本不被考慮。但是,如果我將其從包括更改爲加入,它工作正常。

# Rails 4 format with joins instead of includes. 
class Mobileownerdisclosure < ActiveRecord::Base 
    belongs_to :mobileuser, -> { where("mobileownerdisclosures.mobileowner_type = 'Mobileuser'").joins(:mobileownerdisclosures) }, foreign_key: 'mobileowner_id' 
end 

但自從我從Rails 3的一個非常大的項目轉換爲軌道4,我寧願把它包括像原意,只是要確定原來的編碼器並不需要這種方式。

爲什麼包括不被考慮?除了我在那裏做什麼之外,還有其他的使用方法嗎?

在此先感謝。

+0

檢查此[文檔】(http://apidock.com/rails/ActiveRecord/QueryMethods/references)進行。我認爲你需要添加.references(:mobileownerdisclosures)來讓rails在sql中的where語句中使用joined/eager loaded表。 通過一個連接,你不需要告訴activerecord你在where子句中引用了包含的表/關係。 – user3366016

回答

1

你試過

.eager_load(:mobileownerdisclosures) 

,而不是joins/includes

'包括'現在導致單獨的查詢。因此,您沒有適合您的WHERE條件的連接。

看到http://blog.bigbinary.com/2013/07/01/preload-vs-eager-load-vs-joins-vs-includes.html

+0

謝謝,謝謝neongrau。我想我嘗試了所有「其他」,除了eager_load。哈哈似乎已經做到了。軌道控制檯輸出現在看起來相同,從3到4。 – dsmorey

+0

謝謝neongrau。 – dsmorey