Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix for #317 #423

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions lib/acts_as_list/active_record/acts/list.rb
Original file line number Diff line number Diff line change
Expand Up @@ -386,6 +386,12 @@ def insert_at_position(position, raise_exception_if_save_fails=false)
if in_list?
old_position = current_position
return if position == old_position

# Move 2 after 5 [1, 3, 4, 5, 2] => [1, 3, 4, 5, 6] should be [1, 2, 3, 4, 5].
# Addresses Drag&Drop edge case when moving item to the top of the list.
max_position = acts_as_list_list.maximum(position_column).to_i
position = max_position if position > max_position

# temporary move after bottom with gap, avoiding duplicate values
# gap is required to leave room for position increments
# positive number will be valid with unique not null check (>= 0) db constraint
Expand Down
31 changes: 31 additions & 0 deletions test/shared_list.rb
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,37 @@ def test_insert_at
assert_equal [$default_position, 1, 2, 3, 4, 5], pos_list
end

def test_insert_at_top
new = ListMixin.create(parent_id: 20)
assert_equal 1, new.pos

new = ListMixin.create(parent_id: 20)
assert_equal 2, new.pos

new_noup = ListMixin.acts_as_list_no_update { ListMixin.create(parent_id: 20) }
assert_equal_or_nil $default_position, new_noup.pos

new3 = ListMixin.create(parent_id: 20)
assert_equal 3, new3.pos

new4 = ListMixin.create(parent_id: 20)
assert_equal 4, new4.pos

new4.reload
assert_equal 4, new4.pos

new5 = ListMixin.create(parent_id: 20)
assert_equal 5, new5.pos

## DnD sorting moves item to top by adding after the top item, creating a gap.
## https://github.com/brendon/acts_as_list/issues/317
new3.insert_at(6)
assert_equal 5, new3.pos

pos_list = ListMixin.where(parent_id: 20).order("pos ASC#{' NULLS FIRST' if ENV['DB'] == 'postgresql'}").map(&:pos)
assert_equal [$default_position, 1, 2, 3, 4, 5], pos_list
end

def test_insert_at_after_dup
new1 = ListMixin.create(parent_id: 20)
new2 = ListMixin.create(parent_id: 20)
Expand Down