ruby-on-railsrubyruby-on-rails-3ancestryacts-as-list

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:

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!


Solution

  • It appears as though this issue is already know according to this issue report and has a pull request addressing it. As a short-term fix, I followed Brendon's suggestion posted to the pull request and got around the bug by declaring a custom scope thereby bypassing the scope_changed? method where the bug exists.

    Hopefully this helps someone in the future save some time, and grey hair.