Kein
Kein

Reputation: 996

Rails json response. Int converting to date

I have a problem, with responding data in json. Here is a code:

@data  [
            actions_by_type.each do |action|
              [ action[:date].to_i, action[:activity] ]
            end 
        ]
respond_to do |format|
      format.json { render :json => @data }
    end

But responde is:

...{"date":"2013-04-29T20:20:00Z","activity":"87"}...

Why rails convert my int time, to string datetime?

Upvotes: 0

Views: 152

Answers (2)

Pablo Cantero
Pablo Cantero

Reputation: 6357

You should use .map instead of .each.

@data = actions_by_type.map do |action|
            [ action[:date].to_i, action[:activity] ]
        end 

respond_to do |format|
    format.json { render :json => @data }
end

With .each the result of @data will be the actions_by_type instead of the new array.

Upvotes: 2

mu is too short
mu is too short

Reputation: 434665

x.each returns x so this:

x = actions_by_type.each do |action|
  [ action[:date].to_i, action[:activity] ]
end

is equivalent to:

x = actions_by_type

You want to use map instead of each:

@data = actions_by_type.map do |action|
  [ action[:date].to_i, action[:activity] ]
end 

Upvotes: 2

Related Questions