I have a column in a database with responses to a dropdown "referral source" question. I am querying that and returning a hash:
Clients.count(:all, :group => :referral_source)
Which results in the following hash:
{"Internet search (e.g., Google)?"=>26,
"Personal referral (e.g., friend or family)"=>23,
"Other"=>11, ""=>51,
"Listserv (e.g., neighborhood listserv)"=>5,
"Walk by"=>5}
In the view, I'd like like to plot those results as a bar chart with d3.js. I found this nice with a chart that looks exactly as I would like my chart to look. My problem is the example uses CSV data.
How can I get my data into the format this example uses straight out of rails. In other words, I would like my data to look like an array of objects to pass to javascript in the view:
var data = [ {"Name": "Internet search (e.g., Google)?", "Count": 26},
{"Name": "Personal referral (e.g., friend or family)", "Count": 23},
... ]
How do I modify that hash (or query) to get it into the desired format?
I solved my question by remapping my hash to a new array. Seems like it might be possible to do this with an original query, but I am not strong on Activerecord/SQL to make it happen.
Here is how I remapped the hash to an array of objects that could be used with D3-generator in Ruby
@referral_source = Client.count(:all, :group => :referral_source)
remap = @referral_source.map {|k, v| { Name: k, Count: v} }
=> {{:Name=>"Internet search (e.g., Google)?", :Count=>26}, ... ]
Then I did a .to_json on that in the view. It took me a lot longer than I thought it would to figure out.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With