我有一个Rails变量,我需要提取所有日期和时间(send_time)并放入JS数组中。我正在尝试使用send_times的JS数组来阻止用户将来使用这些日期/时间。考虑安排一小时的会议室。两个会议不能同时进行。

我已经检查了我的JS中的变量。

var taken = <%= @taken.inspect.html_safe %>;


这是检查的变量

    var taken = [

    #<ScheduledRequest _id: 5b7f6b2842195a000400000f, send_time: 2018-08-25 18:00:00 UTC, sent_time: nil, warning_time: 2018-08-25 16:30:00 UTC, actual_send_time: 2018-08-25 16:45:00 UTC, processing: nil, retries: 10, pickup_address: "2209 West Anderson Lane, Boston, MA, USA", dropoff_address: "2209 West Anderson Lane, Boston, MA, USA", round_trip: false, token: nil, pickup_location: [-37.729439, 40.355348], dropoff_location: [-47.729439, 30.355348], notes: "Scheduled: Simple assembly and take away trash.", ip: "XHgw1nn3xIHzfs5t2xzZ/ez0Tj5gg=", notify_email: "", notify_phone: "", user_id: "53f4b008", thingy_type: "Blue Row", thingy_request_id: nil, error: nil, two_hour_warning_sent: nil, identifier: nil, estimated_time: "", thingy_request_log: nil, for_customer_api: false, removed: false, edit_date: "2018-08-25", edit_hours: "01", edit_minutes: "00", edit_ampm: "PM">,

    #<ScheduledRequest _id: 5b7f92964029e90004000013, send_time: 2018-08-28 01:00:00 UTC, sent_time: nil, warning_time: 2018-08-27 23:30:00 UTC, actual_send_time: 2018-08-27 23:45:00 UTC, processing: nil, retries: 10, pickup_address: "5501 Spicewood Springs Road, Boston, MA, USA", dropoff_address: "2345 West Anderson Lane, Boston, MA, USA", round_trip: false, token: nil, pickup_location: [-77.771753, 20.384814], dropoff_location: [-57.7322452, 10.356484], notes: "Scheduled:", ip: "XHgwMmB7fk1lRn1Bg8ooqhwM4xQsg=", notify_email: "", notify_phone: "", user_id: "53f4b08", thingy_type: "Blue Row", thingy_request_id: nil, error: nil, two_hour_warning_sent: nil, identifier: nil, estimated_time: "", thingy_request_log: nil, for_customer_api: false, removed: false, edit_date: "2018-08-27", edit_hours: "08", edit_minutes: "00", edit_ampm: "PM">

    ];


更新:

我剥离了数据并创建了一个新的Ruby数组。

result = []
sr.each do |r|
  record = {}
  record[:send_time] = r.send_time
  record[:ambulance_type] = r.ambulance_type
  result << {:ambulance => record}
end
result


我现在正在用这个。 var taken = <%= @taken.as_json %>;

现在得到这个(擦洗数据以获得敏感信息)。

var taken = [{&quot;thingy&quot;=&gt;{&quot;send_time&quot;=&gt;&quot;2018-08-25T18:00:00.000+00:00&quot;, &quot;thingy_type&quot;=&gt;&quot;Row Delivery&quot;}}

最佳答案

首先,请注意as_jsonto_json之间的区别。 as_json返回一个哈希,然后将其字符串化。 to_json实际上将创建一个JSON字符串。有关更多详细信息和参考,请参见此问题:Difference between as_json and to_json method in Ruby

我建议更新您的ScheduledRequest模型,使其具有一个as_json方法,该方法可以有效地执行更新each内的内容(返回单个ScheduledRequest的哈希表示。)然后,在您看来,您可以

var taken = <%= @taken.to_json.html_safe %>

to_json将返回一个JSON数组,而html_safe将确保它不会得到html编码(这就是您在上面看到的内容)。拉取有关如何表示单个ScheduledRequest对象的逻辑,可以确保该类负责确定如何将其表示为JSON,而不必担心视图。请注意,通过上述分配,您可以使@taken变量在JavaScript中以taken的形式进行访问。

关于javascript - 如何在Javascript中访问Rails变量?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51998320/

10-13 04:42