2013-03-07 76 views
0

我试图从我的数据库通过我的轨道控制器返回一个日期数组,然后在呈现日历时由JavaScript使用。当我拉起轨道控制台进行测试时,似乎工作正常,但不是在视图中。有任何想法吗?我的代码如下。从数据库查询返回Ruby数组到javascript

齿轮的has_many line_items

的LineItem belongs_to的齿轮

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 = <%= @ gear.line_items.rented.flatten.to_json.html_safe%>;

+0

我觉得@ gear.line_items将返回line_items的列表不是单一LINE_ITEM。所以@ gear.line_items.rented wo'nt工作。 – 2013-03-07 05:44:47

回答

2

尝试使用to_json

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

那拉的数据,但遇到奇怪的返回值新的Array(“[[" 2013年2月12日"," 2013年2月13日"," 2013年2月14日"," 2013年2月15日"," 2013 -02-16 "," 2013年2月17日"," 2013年2月18日"," 2013年2月19日"," 2013年2月20日"," 2013年2月21日"],[2013 " -02-05 "," 2013-02-06 "," 2013-02-07 "," 2013年2月8日"," 2013年2月9日"," 2013年2月10日"," 2013年2月11日"," 2013年2月12日"," 2013年2月13日", " 2013-02-14 "," 2013-02-15 "]]“) – DaveG 2013-03-07 05:44:38

+1

@DaveG:或许在最后加上'。 – 2013-03-07 05:48:24

+2

看起来你只是将一个to_json卡在现有代码的末尾。如果你看一下jvnill的回答,那不是他所建议的。你得到一个json数组作为响应,引用它,并创建1个数组的数组(引用的json响应)。 – railsdog 2013-03-07 05:49:40