2017-04-13 130 views
-1

我遵循Railscast關於可排序列表,它完美適用於一個可排序列表。但是當我試圖創建兩個連接的可排序列表時,我發現serialize只能存儲元素的id。有沒有辦法讓序列化商店也清單的ID每個列表元素ID?或者相應地將列表的元素父ID合併到序列化結果中?jQuery可排序列表connectWith序列化?

這個答案jQuery-UI Sortable Connected-Lists save order and association to rails model與我所看到的非常接近,在此之後,我設法在列表之間拖動元素並將其成功保存到數據庫,但排序具有一個列表的元素無法正確保存。

查看

<% @project.tasks.group_by(&:column).each do |column, tasks| %> 
    <ul id='tasks_<%= column %>' data-update-url='<%= sort_project_tasks_url(@project) %>'> 
    <% tasks.sort_by! { |t| t.priority }.each do |task| %> 
     <li id="task_<%= task.id %>"> 
     <%= task.name %>| <%= column %> | <b><%= task.priority %></b> 
     </li> 
    <% end %> 
    </ul> 
<% end %> 

腳本平原序列變異我用。

jQuery -> 
    $('#tasks_done').sortable 
    connectWith: '#tasks_dev' 
    update: -> 
     $.post($(this).data('update-url'), $(this).sortable('serialize')) 

腳本我已經從鏈接的問題。它也能正常工作拖動列表之間的元素,但名單中的排序將不保存正確

jQuery -> 
    $('#tasks_dev').sortable 
    connectWith: '#tasks_done' 
    update: (event, ui) -> 
     neworder = new Array() 
     $(this).children().each -> 
      column = $(this).parent().attr('id') 
      id = $(this).attr('id').match(/((?!task_).)*$/)[1] 
     neworder.push(
      id: id 
     column: column 
     ) 
    $.post($(this).data('update-url'), Activity: JSON.stringify(neworder)) 

相應的控制器動作(不強PARAMS現在),更新的第二個腳本變種

def sort 
    JSON.parse(params[:Activity]).each_with_index do |data, index| 
    id = data['id'] 
    priority = index + 1 
    column = data['column'] 
    column.slice! 'tasks_' # columns ids are tasks_<%= task.column %> 
    task = Task.find(id) 
    task.update_attributes(priority: priority, column: column) 
end 

所以,主要問題是:我無法弄清楚如何在一個列表中保存排序結果,同時跟蹤列表之間的元素移動。在服務器端看起來很容易,但我對前端沒有經驗,並且無法弄清楚如何在客戶端上正確地形成參數。

+1

請閱讀「[問]」和「[mcve]」和他們的李nked頁面。當詢問您的代碼有問題時,我們需要查看重複出現問題的最小代碼。如果沒有這些,我們就不得不設法想象你的代碼,但如果我們不能想象更多的東西,那麼你的工作就不會那麼順利。 –

+0

對不起,更新後的問題。 –

回答

0

所以,這裏是我提出的解決方案。你基本上只是得到列表的ID,追加到它可排序('序列化')結果併發布。

tasks.coffee(我會.erb後重構它)

jQuery -> 
    $('#tasks_done').sortable 
    connectWith: '#tasks_dev' 
    update: -> 
     $.post($(this).data('update-url'), 'column' + '=' + $(this).attr('id') + '&' + $(this).sortable('serialize')) 

jQuery -> 
    $('#tasks_dev').sortable 
    connectWith: '#tasks_done' 
    update: -> 
     $.post($(this).data('update-url'), 'column' + '=' + $(this).attr('id') + '&' + $(this).sortable('serialize')) 

tasts_controller.rb

def sort 
    column = params[:column].delete! 'tasks_' 
    params[:task].each_with_index do |id, index| 
     Task.where(id: id).update_all(priority: index + 1, column: column) 
    end 
end 

形成PARAMS: http://imgur.com/a/tHNj9

(對不起,不有足夠的代表直接添加圖片)