Rails scope如何实现查询所有员工状态均为active的Company实例
原代码问题分析
你写的scope逻辑是匹配到公司至少有1名状态为active的员工就返回,而非所有员工均为active。joins(:employees) + 单条where条件只会过滤符合要求的关联员工行,不会校验该公司下其他员工的状态,因此只要存在1个active员工的公司都会被返回。
正确实现方案
方案1:NOT EXISTS 逻辑(更直观,性能更优)
逻辑为:公司不存在任何状态非active的员工,即为符合要求的公司:
scope :with_active_employees_only, -> { where.not( exists: Employee.select(1) .where("employees.company_id = companies.id") .where.not(status: 'active') ) }
注:该方案默认会包含没有任何员工的公司,如果需要排除这类公司,可以额外加存在员工的过滤条件:
scope :with_active_employees_only, -> { where.exists(Employee.where("employees.company_id = companies.id")) .where.not( exists: Employee.select(1) .where("employees.company_id = companies.id") .where.not(status: 'active') ) }
方案2:GROUP + HAVING 统计
通过分组统计公司下非active员工的数量为0,自动排除没有员工的公司:
scope :with_active_employees_only, -> { joins(:employees) .group('companies.id') .having("COUNT(CASE WHEN employees.status != 'active' THEN 1 END) = 0") }
内容的提问来源于stack exchange,提问作者Paul Heilweck
相关产品推荐
相关产品推荐

