开发者

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_d开发者_如何学Pythonata=#{@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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜