Fix up/down functions

This commit is contained in:
Ari Timonen 2020-03-30 02:16:34 +03:00
parent f6b30be278
commit 4d06c80bfe
2 changed files with 11 additions and 12 deletions

View file

@ -46,13 +46,13 @@ class CategoriesController < ApplicationController
def up def up
raise AccessError unless @category.can_update? cuser raise AccessError unless @category.can_update? cuser
@category.move_up(["domain = ?", @category.domain], "sort") @category.move_up(Category.where(domain: @category.domain), 'sort')
redirect_to :categories redirect_to :categories
end end
def down def down
raise AccessError unless @category.can_update? cuser raise AccessError unless @category.can_update? cuser
@category.move_down(["domain = ?", @category.domain], "sort") @category.move_down(Category.where(domain: @category.domain), 'sort')
redirect_to :categories redirect_to :categories
end end

View file

@ -29,27 +29,26 @@ module Extra
Sanitize.clean(text.to_s).bbcode_to_html.gsub(/\n|\r\n/, "<br>").html_safe Sanitize.clean(text.to_s).bbcode_to_html.gsub(/\n|\r\n/, "<br>").html_safe
end end
def move_up(scope, column = "position") def move_up(objects, column = "position")
n = 0 n = 0
objects = self.class.all(conditions: scope, order: column) # the objects need to be assigned before loop or the order is not right
objects.each do |item| (objects = objects.order(column)).each_with_index do |item, i|
if item.id == id and n > 0 if item.id == id and n > 0
old_position = item[column] old_position = item[column]
item.update_attribute(column, objects.fetch(n-1)[column]) item.update_attribute(column, objects[i-1][column])
objects.fetch(n-1).update_attribute(column, old_position) objects[i-1].update_attribute(column, old_position)
end end
n = n + 1 n = n + 1
end end
end end
def move_down(scope, column = "position") def move_down(objects, column = "position")
n = 0 n = 0
objects = self.class.all(conditions: scope, order: column) (objects = objects.order(column)).each_with_index do |item, i|
objects.each do |item|
if item.id == id and n < (objects.length-1) if item.id == id and n < (objects.length-1)
old_position = item[column] old_position = item[column]
item.update_attribute(column, objects.fetch(n+1)[column]) item.update_attribute(column, objects[n+1][column])
objects.fetch(n+1).update_attribute(column, old_position) objects[n+1].update_attribute(column, old_position)
end end
n = n + 1 n = n + 1
end end