使用Rails中的类方法基于其关联查询模型

时间:2014-03-03 11:15:01

标签: ruby-on-rails ruby activerecord

我正在尝试使用与多个关联模型相对应的多个类方法在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')
=> []

如何在Enrollment上获取类方法以返回与Cohort类方法相同的对象?

1 个答案:

答案 0 :(得分:0)

这应该按照您的预期运作:

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