使用rails处理双重发布请求

时间:2012-06-02 06:11:17

标签: jquery ruby-on-rails ruby-on-rails-3 web-services mongoid

在html中,我有两个带.column类的div。所以,我创建了一个每个循环来为每个.column div序列化数据。

// item.js
$('.column').each(function(){
  update: $.post($(this).data('update-url'), $(this).sortable('serialize'));
});

示例包括item[]=1&item[]=5&item[]=4item[]=2&item[]=3。这些参数将被发送到rails控制器,通过POST进行排序。

在rails控制器中

def sort
  params[:item].each_with_index do |id, index|
    Item.where(_id: id.last).update(position: index+1)
    #Item.where(_id: id.last).update(position: index+4)
  end
  render nothing: true
end

问:如何以干燥的方式处理帖子参数?对于第一个请求(item[]=1&item[]=5&item[]=4),我想用position: index+1更新数据库(mongoid),而第二个请求我希望用position: index+4更新它。感谢。

1 个答案:

答案 0 :(得分:0)

您可以将增量值作为参数发送到表单中。在您的视图中,只需在form代码中添加新的隐藏代码(假设您使用的是ERB):

<%= hidden_field_tag :increment, [INCREMENT_VALUE] %>

并修改您的sort方法,使其类似于

def sort
  params[:item].each_with_index do |id, index|
    Item.where(_id: id.last).update(position: index+1 + params[:increment].to_i)
  end
  render nothing: true
end