diasks2
diasks2

Reputation: 2142

Ruby - how to parse dates in an array

I have an Rails ActiveRecord group query:

a = Product.select("date(date) as date, count(id) as products").group("date(date)").to_a 

and I want to change the format of all of the dates in the array. I thought it would be something like this:

a.map { |s, i| [Date.parse(s).to_time.strftime("%Y-%m-%dT%H:%M:%S"), i] }

However, I am getting a can't convert Product into String error. How can I parse the dates in my array and change their format?

EDIT:

Here is an example of the output I am looking for.

Given this table:

 create_table :products do |t|
       t.date :date
 end

Ultimately, I want to create a json output based on the above group query. Something like:

 [{"products":23,"date":"2012-06-15T00:00:00"}, {"products":26,"date":"2012-06-16T00:00:00"}] 

Upvotes: 2

Views: 3871

Answers (2)

KL-7
KL-7

Reputation: 47678

Try this:

a.map { |s, i| [Date.parse(s.date).to_time.strftime("%Y-%m-%dT%H:%M:%S"), i] }

Your query returns an array of Product objects with two fake fields date and products (same as in the SQL query). To get dates you should call s.date on the elements of the returned array.

EDIT

To get desired array you can do:

query_result = Product.select("date(date) as date, count(id) as products").group("date(date)")

query_result.map do |row| 
  { :products => row.products, :date => Date.parse(row.date).to_time.strftime("%Y-%m-%dT%H:%M:%S") }
end

Upvotes: 3

Jef
Jef

Reputation: 5474

Why don't you serialize your ActiveRecord::Relation to JSON (a.to_json) and let the JSON serializer handle the formatting of the date ?

Product.select("date(date) as date, count(id) as products").
  group("date(date)").to_json

Upvotes: 0

Related Questions