将Ruby数组从数据库查询返回到javascript

时间:2013-03-07 05:39:16

标签: javascript ruby-on-rails ruby arrays

我正在尝试通过我的rails控制器从我的数据库返回一个日期数组,然后在渲染日历时由Javascript使用。当我拉起rails控制台进行测试而不是在视图中时,它似乎正在工作。有任何想法吗?我的代码如下。

Gear has_many line_items

LineItem belongs_to Gear

Javascript变量

var $myBadDates = new Array("<%= @gear.line_items.rented %>");

查看正在返回的内容。

var $myBadDates = new Array("[]");

订单项模型(缩短)

class LineItem < ActiveRecord::Base
  belongs_to :gear

  scope :available, where(:cart_id => nil)

  def self.rented
    LineItem.available.collect {|x| (x.rentstart..x.rentend).to_a}
  end

end

Rails控制台中的数组

1.9.3-p194 :007 > g.line_items.rented
  LineItem Load (0.7ms)  SELECT `line_items`.* FROM `line_items` WHERE `line_items`.`gear_id` = 4 AND `line_items`.`cart_id` IS NULL
 => [[Tue, 12 Feb 2013, Wed, 13 Feb 2013, Thu, 14 Feb 2013, Fri, 15 Feb 2013, Sat, 16 Feb 2013, Sun, 17 Feb 2013, Mon, 18 Feb 2013, Tue, 19 Feb 2013, Wed, 20 Feb 2013, Thu, 21 Feb 2013], [Tue, 05 Feb 2013, Wed, 06 Feb 2013, Thu, 07 Feb 2013, Fri, 08 Feb 2013, Sat, 09 Feb 2013, Sun, 10 Feb 2013, Mon, 11 Feb 2013, Tue, 12 Feb 2013, Wed, 13 Feb 2013, Thu, 14 Feb 2013, Fri, 15 Feb 2013]] 

更新已接受答案中的工作javascript代码

var $ myBadDates =&lt;%= @ gear.line_items.rented.flatten.to_json.html_safe%&gt ;;

1 个答案:

答案 0 :(得分:2)

尝试使用to_json

var $myBadDates = <%= @gear.line_items.rented.to_json %>;