hash - Preparing Data to Plot in d3.js from Ruby on Rails Database -


i have column in database responses dropdown "referral source" question. querying , returning hash:

clients.count(:all, :group => :referral_source) 

which results in 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 view, i'd like plot results bar chart d3.js. found nice d3.js example chart looks chart look. problem example uses csv data.

how can data format example uses straight out of rails. in other words, data array of objects pass javascript in view:

var data = [ {"name": "internet search (e.g., google)?", "count": 26},              {"name": "personal referral (e.g., friend or family)", "count": 23},              ... ] 

how modify hash (or query) desired format?

d3-generator.com nice reference started d3.js. found d3 tutorials useful did not see horizontal bar chart labels there.

i solved question remapping hash new array. seems might possible original query, not strong on activerecord/sql make happen.

here how remapped hash array of objects used 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 did .to_json on in view. took me lot longer thought figure out.


Comments