gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 18:56:43 25 4
gpt4 key购买 nike

我正在尝试通过 Rails Controller 从数据库返回日期数组,然后 JavaScript 在渲染日历时使用该数组。当我拉起 Rails 控制台进行测试时,它似乎可以工作,但在 View 中却不起作用。有任何想法吗?我的代码如下。

装备有_many line_items

订单项属于 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 = <%= @gear.line_items.rented.flatten.to_json.html_safe %>;

最佳答案

尝试使用to_json

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

关于javascript - 将 Ruby 数组从数据库查询返回到 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15263911/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com