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

changing parent_id does not update item positions #126

Closed
richardrails opened this issue Jun 12, 2014 · 1 comment
Closed

changing parent_id does not update item positions #126

richardrails opened this issue Jun 12, 2014 · 1 comment

Comments

@richardrails
Copy link

I have this tree:

parent_id: 1

  • item A position 1
  • item B position 2
  • item C position 3

parent_id: 2

  • item D position 1
  • item E position 2
  • item F position 3

when I change parent_id attribute at item A: parent_id = 2 and save, it does not recalculate item positions of all lists! I get this lists after save:

parent_id: 1

  • item B position 2
  • item C position 3

parent_id: 2

  • item A position 1
  • item D position 1
  • item E position 2
  • item F position 3

and correct lists are:

parent_id: 1

  • item B position 1
  • item C position 2

parent_id: 2

  • item A position 1
  • item D position 2
  • item E position 3
  • item F position 4

Which method should I call to do this right order? Thank you.

@richardrails
Copy link
Author

module ActsAsList
  # positions can get mixed up when users click like crazy -> reorder them if necessary
  # ActsAsList.reorder_positions!(current_user.categories)
  def self.reorder_positions!(objects)
    objects.each_with_index do |object, index|
      new_position = index + 1
      next if object.position == new_position
      object.update_attribute(:position, new_position)
    end
  end
end
  after_save :reorder_list, if: :parentid_changed?
  def reorder_list
    ActsAsList.reorder_positions!(Page.where(parentid: self.parentid).order(:position))
    ActsAsList.reorder_positions!(Page.where(parentid: self.parentid_was).order(:position))
  end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant