G
G
gejarufu2014-05-31 12:27:24
JavaScript
gejarufu, 2014-05-31 12:27:24

How to send a POST request when sorting elements on a page (Nestable)?

Rails 4.1.1
Nestable Error " undefined method `each_with_index` for nil:NilClass " js
when dragging elements in sort method

$('.dd').nestable('serialize');
$('.dd').on('change', function() {
  $.post(
    $(this).data('update-url'),
    $(this).nestable('serialize')
    )
});

view
.dd data-update-url="#{sort_admin_list_pages_path(@list)}"
  ol.dd-list
    - @list.pages.order('position').each do |page|
      li.dd-item data-id="#{page.id}"
        .dd-handle = page.name

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

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dimitriy, 2014-05-31
@Vakiliy

The data that is sent does not contain the parameters pages.
According to the documentation .nestable('serialize'); data-* attributes are being sent, you have data-id, i.e. sent in the form (from the official doc.) [{"id":1},{"id":2},{"id":3,"children":[{"id":4},{"id ":5}]}]
And for some reason you accept pages:
Accordingly, you get an error that there is no each_with_index method for NilClass.
Solution: either send data-pages or receive :id

G
gejarufu, 2014-06-07
@gejarufu

I'm trying to revive the question.
Did so. Maybe you can somehow transfer the array immediately without conversion?

$('.dd').on('change', function() {
 url = $(this).data('update-url'),
 array = $(this).nestable('serialize'),
 $.ajax({
   dataType: 'json',
   url: url,
   type: 'post',
   data: {id: array}
   })
 )
});

In the POST request
Parameters
id[0][id] 1
id[1][id] 2
Source
id%5B0%5D%5Bid%5D=1&id%5B1%5D%5Bid%5D=2
But then it falls to the second line in the method with error
Mysql2::Error: Truncated incorrect DOUBLE value:
def sort
  params[:id].each_with_index do |id, index|
    Page.where(id: id).update_all({position: index+1})
  end
        render nothing: true
end

In the method, as I understand it, sorting will only work for one-dimensional arrays. How to correctly resolve child elements in a method?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question