0

I am trying to implement a dynamic JSON object in a Highcharts function and I am wondering is there a clever ruby way to do this.

Basically I have Users in my rails app, each with a country of origin in the ISO-a2 format. I need to get the numbers of members for each country into this format....(value will be the dynamic variable)

var data = [{"code":"AF","value":"<%= ruby code %>"},
            {"code":"AX",.......and so on

I could start with

       country_array = Array.new
       User.all.map{|u| country_array << u.country}

But my attempts have resulted in horribly long messes. A suggestion if there is a smart way to do this would be great.

2 Answers 2

1
User.all.group_by(&:country).map{|k,v| [k, v.count]}.to_h 

This should give you a Hash with country codes as keys and the number of users having that country code as values.

Sign up to request clarification or add additional context in comments.

Comments

0

You may be able to do this, using the database instead of Ruby to calculate the result:

counts = User.group_by(:country).count.map { |code, count| 
  { "code" => code, "value" => count }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.