如何使用having和group查询ActiveRecord

时间:2015-03-28 11:26:03

标签: ruby-on-rails-4 activerecord group-by having

我有一个简单的约会模型,存储start_time和user_id。我希望在接下来的7天内按升序开始所有约会,并按天分组。理想情况下,结果将是散列或多维数组,例如

{
  '30 March' => 
     [appt1,appt12, appt3],
  '31 March' =>
     [appt5,appt2, appt7,appt8],
  '1 April' => 
     [appt10,appt11,appt9, appt6,appt4],
  '2 April' =>
     [appt15,appt21]
}

下面的查询会获得所需的结果,但不会采用我想要的格式。

Appointment.order(start_time: :asc).where("start_time <= ?", 7.days.from_now.end_of_day)

有没有办法构建查询,还是需要单独格式化结果?

1 个答案:

答案 0 :(得分:0)

执行此操作的一种方法是使用group_by

appointments = Appointment.order(start_time: :asc).
  where("start_time <= ?", 7.days.from_now.end_of_day).
  group_by { |a| a.start_time.to_date }