2012-05-30 47 views
0

我有一個jQuery可排序在我的模型控制器中調用data-update-url,一切都很好,並且函數被調用。 我的排序功能Mongoid Sort and update_all

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

現在,我使用mongoid我知道有沒有完全一樣靈活的方式做我想做的,你可以在SQL。在用戶以他想要的方式拖拽列表中的元素之後,我希望該位置更新,以便用戶列表的順序在會話中保持不變。 上述功能是一個模板,我開始這樣我就可以在正確的方向開始(從railscasts) 我的第一個問題是PARAMS [:文件] .each_with_index,即時流汗拋出

NoMethodError (undefined method `each_with_index' for nil:NilClass): 
    app/controllers/documents_controller.rb:16:in `sort' 

所以我肯定參數[:文檔]是不是我想傳遞給each_with_index方法,但我不確定要嘗試什麼?

更新 document.js.coffee

jQuery -> 
    $('#documents').sortable(
    update: -> 
     $.post($(this).data('update-url'), $(this).sortable('serialize'))); 

相應ERB

<ul id="documents" data-update-url="<%= sort_documents_url %>"> 
    <% @documents.each do |document| %> 
    <%= content_tag_for :li, document do %> 
     <%= render document %> 
    <% end %> 
    <% end %> 
+0

pleasea顯示js和視圖代碼,所以我們看到誰填入網址參數什麼 –

+0

奇怪,現在我得到一個不同的參數,PARAMS [:文檔]似乎傳遞文件的散列,但我得到一個ArgumentError(錯誤數量的參數(2爲1)):現在錯誤,所以進展,我猜它的我n update_all塊 – TheIrishGuy

回答

1
def sort 
    params[:documents].each_with_index do |id, index| 
     doc = Document.find_by_id(id) 
     doc.update_attribute(:position, index) if doc 
    end 
    render nothing: true 
end 
+0

只是更改爲doc = current_user.documents.find(id),它的工作原理是我想要的,非常感謝。 – TheIrishGuy