When a card is dragged inside a list, I'm using thejQueryUI sortable plugin's update callback to send the new position of each card to my controller. This AJAX request posts the position attribute of every card in whichever list the dragged card was released in.
$(".js-Sortable").sortable({
connectWith: ".js-Sortable",
items: ".js-CardContainer",
update: function( event, ui ) {
if (this === ui.item.parent()[0]) {
var data = $(this).sortable('serialize');
$.ajax({
url: "/c/sort",
type: "POST",
dataType: "script",
data: data,
success: function(resp){
console.log('Yay');
}
});
}
}
});
This sends params which look something like this
Parameters: {"card"=>["39", "2", "1", "6", "40", "5", "18", "3", "16", "7", "17", "8", "15", "9", "10", "11", "12", "13", "14", "4"]}
I'm then updating each affected card's position attribute in my controller action like this:
def sort
params[:card].each_with_index do |id, index|
card = Card.find(id)
card.update_attribute(:position, index) if card
end
head :ok
end
The view looks like this:
<ul class="js-CardsContainer js-Sortable">
<% list.cards.order(:position).where(archived: false).each do |card| %>
<li class="js-CardContainer" id="card-<%= card.id %>">
<%= link_to card, class: 'js-Card', :data => { :id => card.id }, remote: true do %>
<span><%= card.title %></span>
<% end %>
</li>
<% end %>
</ul>
This is all working so far. The problem is, cards can be moved across different lists. So, I need to somehow get the id of whichever list the dragged card was released in and post that with the AJAX request too.
I can get the list_id as a variable, but how can I add this list_id to the array in the AJAX request?
datahash<%= link_to card, class: 'js-Card', :data => { :id => card.id,list_id:list.id }, remote: true do %> <span><%= card.title %></span> <% end %>try this and let me