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 - 如何将自动对焦设置为选择下拉列表中的输入?

ruby-on-rails - 适用于 Ruby 的 Linux 发行版

ruby - rake 上的 "desc ' description'"背后的魔法是什么?

ruby-on-rails - rails : new asset path for PDF's not being recognised

ruby - 方法中的递归例程

ruby-on-rails - 如何在 Ruby 中查询方法的结果 (rails)

javascript - asp.net json 显示奇怪的结果

javascript - 将选项作为对象数组进行多项选择

javascript - 何时使用 return,返回的数据会怎样?

ruby-on-rails - cancan & rolify 与 Multi-Tenancy 架构