Rails 3 passing a rails array to javascript function which uses a javascript array

前端 未结 5 884
悲哀的现实
悲哀的现实 2021-02-18 18:12

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

相关标签:
5条回答
  • 2021-02-18 18:49

    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 %>');

    0 讨论(0)
  • 2021-02-18 19:02

    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.

    0 讨论(0)
  • 2021-02-18 19:05

    If you're using HAML, you can just do this:

    var js_array = #{object};

    0 讨论(0)
  • 2021-02-18 19:13

    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.

    0 讨论(0)
  • 2021-02-18 19:15

    Since this still seems like an issue and nobody resolved it. Here goes

    var js_array = [<%= raw @object.to_json %>];
    
    0 讨论(0)
提交回复
热议问题