Rails controller adding quotation marks -
i have openstruct object:
[#<openstruct date="20150602", pageviews="46">, #<openstruct date="20150603", pageviews="44">]
in view, need render in format used charting, [["20150602", 46], ["20150603", 44]]
in view, can achieve like:
-@visits.map |v| ="[#{v.date}, #{v.pageviews}]," and works fine. want in controller, don't need code in view , can insert data.
so try line in controller:
@visits_mapped = @visits.map {|v| "[#{v.date}, #{v.pageviews}],"} however, whole new bunch of quotation marks have been added in when print @visits_mapped in view, no apparent reason:
["[20150602, 46],", "[20150603, 44],"] why behaviour change between view , controller this? forgive me if stupid question...
i'm 95% sure you're making roundabout attempt @ generating json. generate json should use to_json.
visits = [ openstruct.new(date: "20150602", pageviews: "46"), openstruct.new(date: "20150603", pageviews: "44") ] # convert array of openstructs array of two-element arrays, # converting `pageviews` integer while we're @ @visits_mapped = visits.map {|visit| [ visit.date, visit.pageviews.to_i ] } puts @visits_mapped.to_json # => [["20150602",46],["20150603",44]] your comments above suggest want output in data-visits attribute, can conveniently in haml:
#chart_div{ data: { visits: @visits_mapped.to_json } } that template evaluate following html:
<div data-visits='[["20150602",46],["20150603",44]]' id='chart_div'></div>
Comments
Post a Comment