Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
1
rated 0 times [  8] [ 7]  / answers: 1 / hits: 17783  / 13 Years ago, thu, august 25, 2011, 12:00:00

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([#&lt;Mile:0x6ff0cf0&gt;,#&lt;Mile:0x6ff0c18&gt;,#&lt;Mile:0x6ff0b58&gt;])


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.


More From » arrays

 Answers
18

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.


[#90408] Wednesday, August 24, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
calicinthias

Total Points: 447
Total Questions: 101
Total Answers: 118

Location: Botswana
Member since Sat, Dec 31, 2022
1 Year ago
;