Megan Woodruff February 2016

Drag and Drop a collection is rails 4 app: How to get changes to persist?

In my rails app, I have a tasks that has many sub_tasks. One the tasks#show page I have a table that lists all the sub_tasks related to a specific task.

<table>
 <tbody>
    <tr>
    <% @task.sub_tasks.each do |sub_task| %>
    <td><%= sub_task.id %><td>
    <td><%= sub_task.name %><td>
    <td><%= sub_task.description %><td> 
    </tr>
</tbody>
</table>

I've been able to implement a drag and drop on the Task database via http://benw.me/posts/sortable-bootstrap-tables/. However, my question is can a drag and drop be applied to the table of sub_tasks?

Update: added the following and got the list to sort. However, now having trouble getting the array placement to persists.

<table>
 <tbody id="sortable">
    <tr>
    <% @task.sub_tasks.each do |sub_task| %>
    <td><%= sub_task.id %><td>
    <td><%= sub_task.name %><td>
    <td><%= sub_task.description %><td> 
    </tr>
</tbody>
</table>

<script>
$(function (){
 $("#drop").sortable();
});
</script>

I know I have to define a sort method in my Tasks controller, I guess the question is how to pass the position in the @tasks.subtasks array into the params to get these changes to persist?

Answers


Avdept February 2016

If you look into link, that you've provided, there is code, which explains how to do what you asking

$('#sortable').sortable(
      axis: 'y'
      items: '.item'
      cursor: 'move'

      sort: (e, ui) ->
        ui.item.addClass('active-item-shadow')
      stop: (e, ui) ->
        ui.item.removeClass('active-item-shadow')
        # highlight the row on drop to indicate an update
        ui.item.children('td').effect('highlight', {}, 1000)
      update: (e, ui) ->
        item_id = ui.item.data('item-id')
        console.log(item_id)
        position = ui.item.index() # this will not work with paginated items, as the index is zero on every page
        $.ajax(
          type: 'POST'
          url: '/things/update_row_order'
          dataType: 'json'
          data: { thing: {thing_id: item_id, row_order_position: position } }
        )
    )

in update function there is code that is responsible for updating position. You just have to edit url for request and probably add item-id attribute to table elements if you didn't do that. Also you have to take care to update positions of other elements according to currently changed(eg. you moved first element to bottom of table. So all of other elements will get position - 1)

Post Status

Asked in February 2016
Viewed 3,351 times
Voted 11
Answered 1 times

Search




Leave an answer