javascriptruby-on-railscontent-for

How to add to a javascript var array using content_for in Ruby on Rails?


Right now in my code I'm calling content_for like...

<% content_for :javascript do -%> <%= "var boxplot_data=#{@survey.boxplot_answers.to_json};" %> <% end -%>

Rather then having to convert a whole array at once I'd rather add to the array boxplot_data and then have it display as a var. That way I can make my code easier to read because right now where I use that data in my partial isn't near where I generate it to add to the view.


Solution

  • I guess the best approach would be to define a helper:

    def add_to_boxplot(val)
      @boxplot ||= []
      @boxplot << val
    end
    
    def json_boxplot
      "var boxplot_data = #{@boxplot.to_json}"
    end
    

    Then in your view just use add_to_boxplot and in your layout instead of yield(:javascript) use json_boxplot.