按月,按月/年分组

时间:2014-05-01 22:18:53

标签: mysql ruby-on-rails ruby json ruby-on-rails-4

所以我有一个像这样的数据库:

date
11-23-2013
11-24-2013
...
01-05-2014

我正在尝试创建按年份排序然后逐月排序的哈希值,而不重复这些值(例如,11月有30个实例,它应该只显示一次并跳到下个月)。我试图让他们在JSON中显示为:

{2014[05,04,03,02,01], 2013[12,11]}
{12[31,30,29...], 11[30,29,28...]}

我是Rails的新手,到目前为止,这就是我所拥有的:

控制器

 @year = Model.select("year(date) as date").group("year(date)").order("date DESC")
 @month = Model.select("month(date) as date").order("date DESC").group_by{ |m| m.date.year }
 @day = Model.select("day(date) as date").group("day(date)").group_by{ |d| d.date.month }

 respond_to do |format|
      format.html { render :action => :show }
      format.js
      format.json { render :json => {:year => @year, :month => @month, :day => @day}}

月,例如,JSON中显示的内容为:

31557600.0: [{date:1, id:null}]
63115200.0: [{date:2, id:null}]
94672800.0: [{date:3, id:null}]
126230400.0: [{date:4, id:null}]
347133600.0: [{date:11, id:null}]
378691200.0: [{date:12, id:null}]

1 个答案:

答案 0 :(得分:1)

数组group_by方法应该为您执行此操作。

all_dates = Model.order("date DESC").map(&:date)
@months_in_year = all_dates.group_by{|x|x.year}
@months_in_year.each_value {|months| months.map!{|m|m.month}.uniq!}
@days_in_month = all_dates.group_by{|x|x.month}
@days_in_month.each_value {|days| days.map!{|d|d.day}.uniq!}