我有 3 个简单的模型,我们称它们为部门、部门、办公室。部门有很多部门,部门有很多办公室。
现在我想让所有部门至少有一个部门,至少有一个办公室。
我尝试了几种不同的方法,它们“或多或少”起作用。我的意思是如果我调用 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 QUERIES 在我的查询中,我忘了提到两个关联都有一个限制状态的条件子句(如下所示)。
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