参数数量错误的问题

Wrong number of arguments issue

本文关键字:问题 错误 数数 参数      更新时间:2023-09-26

我有以下jQuery可排序代码:

$( ".list" ).sortable({
update: function(){
  $.ajax({
    url: '/books/sort',
    type: 'post',
    items: 'li',
    data: $('.list').sortable('serialize'),
    dataType: 'script',
    complete: function(request){
      alert("jjjj");
    }
  });
}
});

以及我的控制器中的排序操作,例如:

def sort
   params[:book].each_with_index do |id, index|
     Book.update_all({position: index+1}, {id: id})
   end
   render nothing: true
end

但我收到错误:

ArgumentError (wrong number of arguments (2 for 1)):
   app/controllers/books_controller.rb:28:in `block in sort'

如果有人在这里想知道同样的事情,你得到"错误的参数数量"的原因是因为 Rails 发生了变化(我相信是在 4.0 上),移动了您指定条件的部分。

因此,要使其正常工作,您必须使用类似以下内容:

def sort
   params[:book].each_with_index do |id, index|
     Book.where(id: id).update_all({position: index+1})
   end
   render nothing: true
end

其他一切都将按预期工作。

按以下步骤操作

Book.where(id: id).
  update_all(position: index+1)

如果您阅读文档,它明确指出:-

参数:

updates - 表示 SQL 语句的 SET 部分的字符串、数组或哈希。