Oliver
Oliver

Reputation: 1181

Working with JSON in Rails

I have a table called "Weights" that holds a user's weight for a specific day. I can retrieve all relevant data as JSON with the following line of code in my controller's index action:

@weights = Weight.where(:user_id => current_user.id).to_json

The output then looks like:

[{"id":72,"user_id":71,"kilograms":94.0,"day":"2016-06-03","created_at":"2016-06-03T06:58:35.139Z","updated_at":"2016-06-03T06:58:35.139Z"},{"id":75,"user_id":71,"kilograms":34.0,"day":"2016-06-02","created_at":"2016-06-03T13:05:49.862Z","updated_at":"2016-06-03T13:05:49.862Z"},{"id":76,"user_id":71,"kilograms":56.0,"day":"2016-05-29","created_at":"2016-06-03T13:06:01.747Z","updated_at":"2016-06-03T13:06:01.747Z"}]

However, what I would need is an output that looks like:

{2016-06-03 => 94.0, 2016-06-02 => 34.0, 2016-05-29 => 56.0}

How can I achieve this? (I just started coding so I'm sorry if this is a really noob question)

Many thanks.

UPDATE My request refers to a chart I want to display using Chartkick. The documentation says:

Times can be a time, a timestamp, or a string (strings are parsed)

<%= line_chart({20.day.ago => 5, 1368174456 => 4, "2013-05-07 00:00:00 UTC" => 7}) %>

My weights_controller.rb index action now

def index

    result = {}
    Weight.where(:user_id => current_user.id).each do |weight|
      result[weight.day] = weight.kilograms
    end

  end

Thus I need my data in format described above.

Upvotes: 2

Views: 202

Answers (1)

Hieu Pham
Hieu Pham

Reputation: 6707

Let try this:

@result = {}
Weight.where(:user_id => current_user.id).each do |weight|
  result[weight.day] = weight.kilograms
end

Now the result will be a hash:

{'2016-06-03' => 94.0, '2016-06-02' => 34.0, '2016-05-29' => 56.0}

If you want result to be json:

@result.to_json

Update Simply use it in the view for example:

<% @result.each do |day, kg| %>
  <p>Day: <%= day %>, Kg: <%= kg %><p>
<% end %>

Upvotes: 3

Related Questions