[英]Processing double post request with rails
在html中,我具有.column類的2個div。 因此,我創建了一個each循環來序列化每個.column div的數據。
// item.js
$('.column').each(function(){
update: $.post($(this).data('update-url'), $(this).sortable('serialize'));
});
示例為item[]=1&item[]=5&item[]=4
和item[]=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
問:如何以DRY方式處理發布參數? 對於第一個請求( item[]=1&item[]=5&item[]=4
),我想使用position: index+1
更新數據庫(mongoid),而第二個請求,我希望使用position: index+4
更新它position: index+4
。 謝謝。
您可以在表格中將增量值作為參數發送。 在您的視圖中,只需在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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.