我有一个 js.coffee.erb 文件,在这个文件中有一个函数可以获取“设备”json 对象(在 JavaScript 中)并将一些数据粘贴到 html 中。
json 对象保存在名为 eqp
的变量中。
每个设备都有一个类别
(引用其他表对象)。
在json对象中,只有equipment.category_id
,因此为了获取类别名称,我编写了以下语句:
$("#display_equipment_category_value").html <%= Category.find(eqp.category_id).name %>
问题是它无法定义名为 eqp
的 Rails 变量,因为它不是 Rails 对象。
如何将 js json eqp.category_id
保存在 Rails 变量中?
set_equipment = (eqp) ->
<% cat_id = ????? %> - # save the eqp.category_id into cat_id
$("#display_equipment_category_value").html <%= Category.find(cat_id).name %>
最佳答案
我不确定这是否是正确的答案,因为它似乎无效,但它工作正常,所以我会使用它:
set_equipment = (eqp) ->
// Creating an empty string variable for the result category name
cat = "";
// Bringing all categories from DB and save them as a json object
<% all_cat = Category.all %>
categories = <%= all_cat.to_json %>
// Comparing each category to the equipment category_id
$.each categories, (i, v) =>
cat = v.name if (v.id == eqp.category_id)
// Display the category name in the html
$("#display_equipment_category_value").html cat
关于javascript - 将 CoffeeScript json 对象数据保存在 Rails 变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32865184/