ruby - 如何将参数从嵌套的rails表单发送到jQuery?

时间:2017-06-19 16:30:02

标签: javascript jquery ruby-on-rails ruby twitter-bootstrap

我在Rails中有一个嵌套的表单,最深的部分是这样的:

<%= f.fields_for :character_traits do |attr_f| %>
  <% if attr_f.object.field_name == field %>
    <%= attr_f.number_field :field_value, :disabled => (true if action_name == "show"), data: {toggle: 'popover', title: attr_f.object.field_name, content: description_for_trait(attr_f.object) }, class: :numb %>
  <% end %>
<% end %>

这段代码允许我使用Bootstrap popovers,但我想添加和修改这些描述(保存在descriptions表中并通过辅助方法description_for_trait(attr_f.object)提取)动态,这带来了我来jQuery。

我添加了https://github.com/wrdieter/jquery_context_menu-rails并定义了一个菜单,该菜单成功地将条目添加到descriptions表中。在application.js我写道:

//= require jquery.contextMenu.js
$(document).ready(function() {
  $('.has-tooltip').tooltip();
  $('*').popover({
    trigger: 'click'
  });

$.contextMenu({
            selector: '.numb', 
            callback: function(key, options) {
              if(key = "edit") {
                $.ajax({
                  type: "POST",
                  url: "/descriptions",
                  dataType: "json",
                  data: { description:{character_trait_id: 9303, trait_desc: 'This is my meeey'}}
                  }
                )
              }
              else {
                alert("Not implemented yet..."); 
              }
            },
            items: {
                "edit": {name: "Edit", icon: "edit"},
                "cut": {name: "Cut", icon: "cut"},
               copy: {name: "Copy", icon: "copy"},
                "paste": {name: "Paste", icon: "paste"},
                "delete": {name: "Delete", icon: "delete"},
                "sep1": "---------",
                "quit": {name: "Quit", icon: function(){
                    return 'context-menu-icon context-menu-icon-quit';
                }}
            }
        });

        $('.numb').on('click', function(e){
            console.log('clicked', this);
        })
});

这允许我在descriptions表中添加一个条目,即

  create_table "descriptions", force: :cascade do |t|
    t.integer  "character_trait_id"
    t.text     "trait_desc"
    t.datetime "created_at",         null: false
    t.datetime "updated_at",         null: false
  end

但我遇到了一个问题。我需要知道id我是否想要添加描述的特征。现在我只是在我的jQuery函数中硬编码这些id,但我必须以某种方式动态地获取它们。在Rails中,我可以像这样得到这些ID:

attr_f.object.id

但是我怎样才能在jQuery中获得这个id?也许,如果不可能,我可以以某种方式发送id

0 个答案:

没有答案