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

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}]

最佳答案

数组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!}

10-07 14:39