2011-03-17 56 views
1
active_courses_past_week = CourseEnrollment.select("courses.*"). 
joins(:course). 
where("date(course_enrollments.created_at) BETWEEN ? and ?", Date.parse(start_date.strftime('%Y-%m-%d')), Date.parse(end_date.strftime('%Y-%m-%d'))). 
group("courses.id") 

上述查詢似乎很奇怪,因爲我從課程註冊查詢,但只關心他們在兩個日期之間註冊的課程數據。這似乎很奇怪,因爲我沒有使用CourseErnollment模型中的任何字段。有什麼建議麼?Ruby On Rails查詢從模型中返回另一個表格字段

回答

2

這就是我將如何使用範圍而不是「原始」SQL編寫它。

active_courses_past_week = CourseEnrollment.where(:created_at => start_date..end_date)) 
              .joins(:course) 
              .group(courses.id) 
+0

+1用於重構。你忘了'group(「courses.id」)' – fl00r 2011-03-17 14:01:36

相關問題