我有一個Rails的ActiveRecord的組查詢分析日期:紅寶石 - 如何在一個數組
a = Product.select("date(date) as date, count(id) as products").group("date(date)").to_a
,我想改變陣列中所有日期的格式。我認爲這將是這樣的:
a.map { |s, i| [Date.parse(s).to_time.strftime("%Y-%m-%dT%H:%M:%S"), i] }
但是,我得到一個can't convert Product into String
錯誤。我如何解析數組中的日期並更改其格式?
編輯:
這裏是我要找的輸出的一個例子。
對於這個表:
create_table :products do |t|
t.date :date
end
最後,我想創建基於以上組查詢JSON輸出。喜歡的東西:
[{"products":23,"date":"2012-06-15T00:00:00"}, {"products":26,"date":"2012-06-16T00:00:00"}]
謝謝。這有助於轉換日期。但是,現在我的陣列對每個i值都顯示爲零。例如:'<%= debug a%>'yield'!ruby/object:產品屬性:!binary「ZGF0ZQ ==」:'2012-05-27'!binary「Y2hlY2t0ZXN0cw ==」:1';但是,'<%= a.map {| s,i | [Date.parse(s.date).to_time.strftime(「%Y-%m-%dT%H:%M:%S」),i]}%>'yield'[[「2012-05-27T00 :00:00「,無]]'。爲什麼i值變爲零? – diasks2
那麼,我仍然不確定你期望在這個塊的'i'參數中得到什麼。 ['Array#map'](http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-map)方法只傳入單個參數到塊中 - 當前元素的陣列。對於你的例子,這意味着你在's'參數中獲得了當前的'Product',而在第二個'i'參數中沒有任何東西。 –
對不起,我感到困惑。我的目標是最終得到一組哈希值:a = Product.select(「date(date)as date,count(id)as products」)。group(「date(date)」)。to_a'代替日期格式爲yyyy-mm-dd,格式爲yyyy-mm-ddThh:mm:ss。如果不是最好的方法,它不一定要使用'Array#map'。 – diasks2