我有3个简单的模型,我们称之为Sector,Department,Office。 部门有很多部门和部门有很多办事处。
现在我想让所有部门至少拥有一个至少设有办公室的部门。
我尝试了几种不同的方式,他们“或多或少”工作。我的意思是,如果我调用Sector.with_offices,我得到了我想要的东西但是如果我链接一些非常常见的方法,例如.size(它为原始查询添加了一个计数),我得到了意想不到的结果。在这里我尝试过:
scope :with_offices, joins(:departments => :offices).group('sectors.id')
scope :with_offices, joins(:departments => :offices).select("DISTINCT sectors.*")
我也尝试过使用uniq
:
scope :with_offices, joins(:departments => :offices).uniq
但是,它有同样的问题。
Sector.with_offices.size # => 5 (WRONG VALUE)
s = Sector.with_offices # => [#<Sector ... >]
s.size # => 3 (RIGHT VALUE)
如果我链的大小我得到错误的数字。
什么是一个干净的方式来获得有办公室的部门并保持规模按预期工作?
更新1 - SQL查询 在这里我的查询,我忘了提到两个关联都有一个限制状态的条件子句(如下所示)。
irb(main):010:0> Sector.with_offices.size
(0.6ms) SELECT DISTINCT COUNT(*) FROM "sectors" INNER JOIN "departments" ON "departments"."sector_id" = "sectors"."id" AND departments.state IN ('active', 'deactivated') INNER JOIN "offices" ON "offices"."department_id" = "departments"."id" AND offices.state IN ('active', 'deactivated') WHERE "sectors"."state" IN ('active', 'deactivated')
=> 5
irb(main):011:0> s = Sector.with_offices
Sector Load (0.6ms) SELECT DISTINCT "sectors".* FROM "sectors" INNER JOIN "departments" ON "departments"."sector_id" = "sectors"."id" AND departments.state IN ('active', 'deactivated') INNER JOIN "offices" ON "offices"."department_id" = "departments"."id" AND offices.state IN ('active', 'deactivated') WHERE "sectors"."state" IN ('active', 'deactivated')
更新2 - 协会
Class Sector < ActiveRecord::Base
has_many :departments , conditions: ["departments.state IN ('active', 'deactivated')"]
end
Class Department < ActiveRecord::Base
has_many :offices , conditions: ["offices.state IN ('active', 'deactivated')"]
end
答案 0 :(得分:1)
我尝试了它并且它是3.2.12中的一个错误,显然已在3.2.13中修复。如果升级到3.2.13,将生成正确的SQL。