使用 Rails 中的类方法根据模型的关联查询模型



我正在尝试使用对应于多个关联模型的多个类方法在Rails中创建ActiveRecord查询。 我使用的代码如下

#cohort.rb    
def self.cohort_within_times (from_date, to_date)
  where("start_date >= ? AND end_date <= ?", from_date, to_date)
end

#enrollment.rb
def self.enrollment_within_times (from_date, to_date)
  joins(:cohort) & Cohort.cohort_within_times(from_date, to_date)
end

Cohort有很多Enrollments.

当我打电话给Cohort.cohort_within_times(<valid dates>)时,我得到了有效的回复。 但是,当我调用Enrollments.enrollments_within_times(<same valid dates>)时,我得到一个空数组作为响应。 完整输出如下:

Enrollment.enrollment_within_times("Jan 1st 2013".to_date, "May 31st 2014".to_date)
  Enrollment Load (0.3ms)  SELECT "enrollments".* FROM "enrollments" INNER JOIN "cohorts" ON "cohorts"."id" = "enrollments"."cohort_id"
  Cohort Load (0.3ms)  SELECT "cohorts".* FROM "cohorts" WHERE (start_date >= '2013-01-01' AND end_date <= '2014-05-31')
=> []

如何让注册上的类方法返回与队列类方法相同的对象?

这应该按预期工作:

def self.enrollment_within_times(from_date, to_date)
  where(cohort_id: Cohort.cohort_within_times(from_date, to_date).map(&:id))
end

或者,您可以使用joins方法:

def self.enrollment_within_times(from_date, to_date)
  joins(:cohort).where('cohorts.start_date >= ? AND cohorts.end_date <= ?', from_date, to_date)
end

最新更新