0

假设我有以下型号:

class Employee < ActiveRecord::Base
    has_many :shifts    
end

class Shift < ActiveRecord::Base
    belongs_to :employee
end

在我的控制器中,我想加载所有员工,包括他们在某个日期范围内的班次。但我也想包括在该范围内没有任何轮班的员工。

在我的控制器中,我尝试了:

@employees.joins("LEFT OUTER JOIN shifts ON employees.id = shifts.employee_id").where('shifts.starts_at BETWEEN ? and ?', weekBegin, weekEnd).to_json(:include => :shifts)

但这仍然只是返回在该日期范围内轮班的员工。我还想返回在该日期范围内没有轮班的员工。

这样的查询是如何工作的?

4

2 回答 2

4

您应该将班次开始时间的条件包含在 join 语句中:

@employees.joins("
     LEFT OUTER JOIN shifts 
     ON employees.id = shifts.employee_id
     AND shifts.starts_at 
         BETWEEN #{ActiveRecord::Base.sanitize(weekBegin)} 
             AND #{ActiveRecord::Base.sanitize(weekEnd)}
").to_json(:include => :shifts)
于 2012-07-13T11:59:37.300 回答
1

你可以尝试这样做

LEFT OUTER JOIN shifts ON employees.id = shifts.employee_id AND shifts.starts_at BETWEEN weekBegin and weekEnd
于 2012-07-13T11:44:11.190 回答