2016-08-17 73 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