Just in case anyone wants help using acts_as_list with ancestry #14

Closed
brendon opened this Issue Feb 14, 2010 · 6 comments

Comments

Projects
None yet
2 participants

brendon commented Feb 14, 2010

Hi Stefan, couldn't see a wiki for this repo so I'll post it here. I ended up having to add my own methods for move to right/left/child of which took into account ancestry and acts_as_list. I'm just posting them here in case anyone else wants to use them. These were just put in the model iteself.

# Accepts the typical array of ids from a scriptaculous sortable. It is called on the instance being moved
def sort(array_of_ids)
if array_of_ids.first == id.to_s
  move_to_left_of siblings.find(array_of_ids.second)
else
  move_to_right_of siblings.find(array_of_ids[array_of_ids.index(id.to_s) - 1])
end
end

def move_to_child_of(reference_instance)
transaction do
  remove_from_list
  self.update_attributes!(:parent => reference_instance)
  add_to_list_bottom
  save!
end
end

def move_to_left_of(reference_instance)
transaction do
  remove_from_list
  reference_instance.reload # Things have possibly changed in this list
  self.update_attributes!(:parent => reference_instance.parent)
  reference_item_position = reference_instance.position
  increment_positions_on_lower_items(reference_item_position)
  self.update_attribute(:position, reference_item_position)
end
end

def move_to_right_of(reference_instance)
transaction do
  remove_from_list
  reference_instance.reload # Things have possibly changed in this list
  self.update_attributes!(:parent => reference_instance.parent)
  if reference_instance.lower_item
    lower_item_position = reference_instance.lower_item.position
    increment_positions_on_lower_items(lower_item_position)
    self.update_attribute(:position, lower_item_position)
  else
    add_to_list_bottom
    save!
  end
end   
end
Owner

stefankroes commented Mar 1, 2010

If you feel in any way compelled to create this wiki, or add something to the README on this, please do! :-)

brendon commented Mar 1, 2010

Hi Stefan, I'd love to add this to the repo's wiki, but I think you need to enable it (under Admin/Features). :) It's probably a bit complicated for the README :)

Owner

stefankroes commented Mar 1, 2010

I enabled the wiki

brendon commented Mar 2, 2010

All done :D

Owner

stefankroes commented Mar 2, 2010

great, thx m8, closing ticket

Owner

stefankroes commented Mar 2, 2010

BTW, you might wanna use

self.update_attributes!(:parent_id => reference_instance.parent_id)

Saves you a query.

This issue was closed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment