2014-05-01 170 views
0

所以我有一個數據庫,像這樣:集團月份又一年,月天/年

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

陣列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!} 
+0

嗨,對不起,好點...第一行應該是創建一個日期數組,而不是一組記錄。現在修復。 – SteveTurczyn

+0

很好,它工作。謝謝! –