mardi 29 janvier 2019

How to move all values above or below an insertion up one or down one in a hash

This is for a drag and drop, I have the front end working correctly and it sends data correctly to my rails backend.

I am attempting to sort a hash based on the index position that is incoming as well as only sort the Tasks that are part of the selected column @tasks = Task.where(column_id: params[:column_id]), If an index moves up the list, only update the values that are greater, and if the index moves down the list, only the values that are smaller need to be updated.

I have put comments in the code to explain what it is I believe I am doing.

I have tried many different variations of this loop, with this leading to the closest result but not quite right.

def update
  @tasks = Task.where(column_id: params[:column_id]) #get all tasks with 
column_id
  @task = Task.find(params[:id])
  if(@task[:index] < params[:index]) #current index less than incoming index
   @tasks.each do |t, v|
     next if t[:id].to_i == params[:id].to_i #skip each if t = current task
      if t[:index].to_i <= params[:index].to_i && t[:index].to_i > @task[:index].to_i 
      #if current task index is less than incoming index and current task index is less than @task index
        t.update_attribute(:index, t[:index].to_i - 1) #update task index to old index - 1
      end
    end
  else
  @tasks.each do |t, v|
    next if t[:id].to_i == params[:id].to_i //skip each if t = current task
      if t[:index].to_i >= params[:index].to_i && t[:index].to_i < @task[:index].to_i
      #if current task index is greater than incoming index and current task index is less than @task index
        t.update_attribute(:index, t[:index].to_i + 1) #update task index to old index + 1
      end
    end
  end
  @task.update_attribute(:index, params[:index].to_i)
  if @task.update(task_params)
    render json: Task.where(tasklist_id: params[:tasklist_id])
  else
    render json: @task.errors, status: :unprocessable_entity
  end
end

I excpect the index of the task to change from 1 to 5, and every value underneath to move down one, or change 5 to 1 and every value above move up one

Aucun commentaire:

Enregistrer un commentaire