javascript - 将 CoffeeScript json 对象数据保存在 Rails 变量中

标签 javascript ruby-on-rails ruby json coffeescript

我有一个 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/

相关文章:

javascript - 使用 URL.Action 帮助程序生成 URL 并正确编码 JavaScript 变量

javascript - Angularjs 中始终为真的测试失败——Karma

ruby-on-rails - 更新的 ruby​​ 和 rails 给 .new .update 方法带来错误

mysql - SQL 查询中的语法错误。无法发现错误

ruby-on-rails - 使用 Rspec 测试 Sidekiq worker

ruby - 从 1.9.3 开始,如何在 Ruby 中获取 YAML 以将 ASCII-8Bit 字符串转储为字符串?

javascript - 将一个输入替换为另一个动态创建的输入

javascript - 前置内容

mysql - 按 2 个参数搜索

ruby-on-rails - 从联系表(rails)保存数据