jeudi 13 août 2015

Rails: Ancestry + Acts_as_List Gems Not Working as Expected When Changing Parent Object

I have a Ruby on Rails 3 app which uses the ancestry gem to provide a hierarchical tree structure for a model in combination with the acts_as_list gem to provide explicit positioning within each level of the hierarchy.

class Obj < ActiveRecord::Base
    ...
    has_ancestry
    acts_as_list scope: [:ancestry]
    ...
end

Furthermore, I am using the following method on the object to change the parent of the object:

# Credit to the author of the ancestry gem for the code.
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

Everything works as expected when:

  • Changing the position of an object within the same parent.
  • Changing the parent of the object when the object has no descendants.

The issue I'm having is that changing the parent of an object that also has descendants causes acts_as_list to not only change the position on the object but also change the position of all descendant objects as well. This causes the position of all descendant objects to act/be unreliable and incurs unnecessary database calls.

Is there any way to prevent this from happening, or is this expected behaviour?

Any help would be greatly appreciated; thanks!

Aucun commentaire:

Enregistrer un commentaire