【问题标题】:Update Rails Model with Json使用 Json 更新 Rails 模型
【发布时间】:2012-12-30 16:36:03
【问题描述】:

目前,我正在实现一个包含项目(slot_allocations)的表。这些项目基于 Rails 模型。 表格中的项目可以拖放。

现在,我可以在我的表中检索和显示模型的数据。 但是,我还想在成功将项目拖放到新单元格后更新模型中的信息,并想就如何执行此操作寻求建议。

我目前能够根据以下 Jquery 代码将信息放入数组中。

 var slot_allocation= []; //array storing info
 $.getJSON('slot_allocations', function(data) { //get json method, put the items in the slot_allocation array.
    $.each(data, function(i, item) {
    slot_allocation.push(item);
 });

 //some extra methods for table creation etc.
 createSubjectsTable($("#subjects"),timeslots,subjects);
 makeDraggable();
 });

对于我可以查看哪些 JQuery 方法或我可以更改代码的哪些区域以更新模型,我将不胜感激。提前致谢。

根据要求提供其他代码。整个代码虽然很长。这是删除它后应该更新模型的部分。我更新数组的尝试是注释后的代码。

$('.Empty').droppable({
  accept: '.Group',
  tolerance: 'pointer',
  drop: function(event,ui){
    ui.droppable = $(this);
    var new_alloc_info = ui.droppable.attr("id")
    var array = new_alloc_info.split('--');
    var timeslot = array[1];
    var subject = array[2];

    var old_alloc_id = ui.draggable.attr("id");
    var array2 = old_alloc_id.split('--');
    var alloc_id = array2[3];

//This is the part where I want to update the rails model
    slot_allocation[alloc_id-1].timeslot=timeslot; 
    slot_allocation[alloc_id-1].subject=subject;        

    var allocText = "alloc--"+timeslot+"--"+subject+"--"+alloc_id;
    ui.draggable.attr("id",allocText);
    ui.draggable.insertBefore(ui.droppable);

  }
})

【问题讨论】:

  • 刚想到这个,但我不确定它是否会起作用。如果我要在以下代码 sn-p 中引用数据,而不是将其推入新数组。 json会更新模型中的信息吗?
  • makeDraggable 的代码在哪里?使用 jQueryUI?任何帮助都取决于该代码中的事件处理。还需要了解有关 html 输出的一些信息,以便能够引用标识符以便将数据发回。发布一些示例行 html 输出
  • 好的,我马上做。
  • 代码是我要更新模型的部分。是的,我正在使用 jQueryUi 进行拖放。我想在项目基本放入新单元格后更新它。

标签: ruby-on-rails ajax json jquery


【解决方案1】:

好的。在drop 回调中,您可以向服务器发出 AJAX 请求。无需试图弄清楚你所有的数组是什么,就从简单的情况开始

/* receive id and time params at server as you would form field "name" */ 
var dataToServer={ id: alloc_id, time: timeslot};

/* can use $.get or */
$.post( url, dataToServer, function( response){
    /* AJAX completed successfully, can access response data here*/
}/* dataType argument here if want to use JSON or XML response*/)

$.post$.get 都是$.ajax 的快捷方式,根据需要有很多选项可供选择

jQuery AJAX API:http://api.jquery.com/category/ajax/

【讨论】:

  • 非常感谢。我会试试这个并回复你。
  • 如果第一次尝试 AJAX...了解如何使用浏览器控制台检查请求以进行故障排除。可以查看发送和接收的所有数据、状态、标头等。可能在第一次遇到错误时,控制台有助于隔离服务器与脚本问题
  • 感谢您的建议!我正在使用它,它确实帮助我更好地理解 ajax 请求。对此感激不尽。我已经发送了请求,但仍然面临数据处理问题,这可能需要在 Rails 中解决。我也在使用 $.ajax 而不是快捷方式。因此,感谢您的所有帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-04-18
  • 1970-01-01
  • 1970-01-01
  • 2018-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多