From 2314e41474b8d15fa7fa496de2b93875429adb5e Mon Sep 17 00:00:00 2001 From: Jean-Philippe Lang Date: Sat, 9 Jun 2012 07:27:43 +0000 Subject: [PATCH] Priorities have the same position and can't be reordered (#11098). git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/trunk@9781 e93f8b46-1217-0410-a6f0-8f06a7374b81 --- .../lib/active_record/acts/list.rb | 11 +++++++- test/unit/issue_priority_test.rb | 27 ++++++++++++++++++- 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/lib/plugins/acts_as_list/lib/active_record/acts/list.rb b/lib/plugins/acts_as_list/lib/active_record/acts/list.rb index 01b414a1c..cd4658c59 100644 --- a/lib/plugins/acts_as_list/lib/active_record/acts/list.rb +++ b/lib/plugins/acts_as_list/lib/active_record/acts/list.rb @@ -131,6 +131,15 @@ module ActiveRecord when 'lowest' move_to_bottom end + reset_positions_in_list + end + + def reset_positions_in_list + acts_as_list_class.where(scope_condition).reorder("#{position_column} ASC, id ASC").each_with_index do |item, i| + unless item.send(position_column) == (i + 1) + acts_as_list_class.update_all({position_column => (i + 1)}, {:id => item.id}) + end + end end # Removes the item from the list. @@ -209,7 +218,7 @@ module ActiveRecord def bottom_item(except = nil) conditions = scope_condition conditions = "#{conditions} AND #{self.class.primary_key} != #{except.id}" if except - acts_as_list_class.find(:first, :conditions => conditions, :order => "#{position_column} DESC") + acts_as_list_class.where(conditions).reorder("#{position_column} DESC").first end # Forces item to assume the bottom position in the list. diff --git a/test/unit/issue_priority_test.rb b/test/unit/issue_priority_test.rb index 349cc2e4b..96d58196c 100644 --- a/test/unit/issue_priority_test.rb +++ b/test/unit/issue_priority_test.rb @@ -47,5 +47,30 @@ class IssuePriorityTest < ActiveSupport::TestCase def test_option_name assert_equal :enumeration_issue_priorities, IssuePriority.new.option_name end -end + def test_should_be_created_at_last_position + IssuePriority.delete_all + + priorities = [1, 2, 3].map {|i| IssuePriority.create!(:name => "P#{i}")} + assert_equal [1, 2, 3], priorities.map(&:position) + end + + def test_reset_positions_in_list_should_set_sequential_positions + IssuePriority.delete_all + + priorities = [1, 2, 3].map {|i| IssuePriority.create!(:name => "P#{i}")} + priorities[0].update_attribute :position, 4 + priorities[1].update_attribute :position, 2 + priorities[2].update_attribute :position, 7 + assert_equal [4, 2, 7], priorities.map(&:reload).map(&:position) + + priorities[0].reset_positions_in_list + assert_equal [2, 1, 3], priorities.map(&:reload).map(&:position) + end + + def test_moving_in_list_should_reset_positions + priority = IssuePriority.first + priority.expects(:reset_positions_in_list).once + priority.move_to = 'higher' + end +end