问题
I am trying to pass a rails array to a javascript function. The function will then use the array values in javascript so I need to keep it an array.
Here is how I am passing my array:
"graphit([<%=@mpg_values.join(",") %>])"
This produces this in the HTML
"graphit([#<Mile:0x6ff0cf0>,#<Mile:0x6ff0c18>,#<Mile:0x6ff0b58>])"
Which are not the values, they should be decimal numbers. I assume this is because it is a reference to the array so that I why I am getting the messed up values. If I do something like to_s I see the values but it has other stuff like the table and filed name in there as well.
Anybody know how I can get this rails array to a javascript function as an array?
Thanks in advance for any help.
回答1:
Since this still seems like an issue and nobody resolved it. Here goes
var js_array = [<%= raw @object.to_json %>];
回答2:
Use Ruby's collect
Method.
A cleaner version of your solution, Xaxum, would be something like this:
def chart_values
@mpg_values.collect do |mpg_value|
[ mpg_value.date.to_s, mpg_value.mpg.round(2).to_f ]
end
end
The collect
method automatically generates an array of whatever the block results in, so you'll end up with something like this:
[
[2011-05-20, 18.56],
[2011-06-01, 18.47]
]
I also changed the mpg
value to use to_f
, which provide a number instead of a string.
回答3:
Going to JSON as suggested a couple times in this post always gave me something like this.
[{"mile":{"date":"2011-05-20","mpg":"18.565887006952"}},{"mile":{"date":"2011-06-01","mpg":"18.471164309032"}}]
What I really wanted was just this... [[2011-05-20, 18.56][2011-06-01, 18.47]]
So I handled it with a helper like so.
def chart_values()
@chart_values = '['
@mpg_values.each do |m|
@chart_values = @chart_values+'['+m.date.to_s+', '+m.mpg.round(2).to_s+'],'
end
@chart_values = @chart_values+']'
end
Then passed chart_values() to the javascript.
Likely not the best solution but it gave me the desired values in the format I needed.
回答4:
If you're using HAML, you can just do this:
var js_array = #{object};
回答5:
bokor's answer works, but causes some linter and IDE errors if you want the array to be saved to a const
, instead of a var
/ let
.
The following variation seems to work and be compliant with the linters and IDEs that I am using.
const js_array = JSON.parse('<%= raw @object %>');
来源:https://stackoverflow.com/questions/7195943/rails-3-passing-a-rails-array-to-javascript-function-which-uses-a-javascript-arr