简体   繁体   中英

Rails controller adding quotation marks

I have an Openstruct object:

[#<OpenStruct date="20150602", pageviews="46">, #<OpenStruct date="20150603", pageviews="44">]

In my view, I need to render in a format to be used for charting, so something like [["20150602", 46], ["20150603", 44]]

In my view, I can achieve this with something like:

-@visits.map do |v|
  ="[#{v.date}, #{v.pageviews}],"

And it works just fine. But I want it in the controller, so I don't need all that code in the view and I can just insert it into the data.

So I try this line in the controller:

@visits_mapped = @visits.map {|v| "[#{v.date}, #{v.pageviews}],"}

However, now a whole new bunch of quotation marks have been added in when I print @visits_mapped in the view, for no apparent reason:

["[20150602, 46],", "[20150603, 44],"]

Why would the behaviour change between the view and the controller like this? Forgive me if this is a stupid question...

The behavior has not changed. In the view you are just not seeing the output of map. Map iterates the members of an array and produces a new array holding the results of the iterations.

In the view you are getting what you 'expected' because you are discarding the final result of map and instead are showing the results of each iteration. Since they are shown with nothing in between them, the output in the view 'looks' right (but should be missing the outer array [] and should have an extra , after the last element). You can get the same result in the view if you change the map to each (which should be more efficient as it wont generate the resulting array). So in the view:

    -@visits.each do |v|
      ="[#{v.date}, #{v.pageviews}],"

Or in the controller:

    @visits_mapped = @visits.map{ |v| [ v.date, v.pageviews ] }

I'm 95% sure you're just making a really roundabout attempt at generating JSON. To generate JSON you should always use to_json .

visits = [ OpenStruct.new(date: "20150602", pageviews: "46"),
           OpenStruct.new(date: "20150603", pageviews: "44") ]

# Convert the array of OpenStructs to an array of two-element arrays,
# converting `pageviews` to an integer while we're at it
@visits_mapped = visits.map {|visit| [ visit.date, visit.pageviews.to_i ] }

puts @visits_mapped.to_json
# => [["20150602",46],["20150603",44]]

Your comments above suggest that you want the output to be in a data-visits attribute, which you can conveniently do like this in Haml:

#chart_div{ data: { visits: @visits_mapped.to_json } }

That template will evaluate to the following HTML:

<div data-visits='[["20150602",46],["20150603",44]]' id='chart_div'></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM