views:

156

answers:

0

I am using awesome_nested_set but I guess this applies to all the nested_set plugins equally.

When I add a child I want that child to inherit some attributes from the parent. Sounds simple, it certainly is with acts_as_tree. The problem is you need to save the object before adding to the parent, so at least initially you end up with a record/object being a root node until it is moved to the correct position in the nested set.

My solution is to have an attribute called proposed_parent which is set before save, an after_save filter then calls move_to_proposed_parent which moves the item to the correct position. I then call a method, inherit_from_parent which copies the inheritable attributes from the parent.

This works fine but is a little messy, I'd like to know if there is a better way of going about this?

def move_to_proposed_parent
    if parent_id.nil? and (not proposed_parent.nil?)
      raise "Set proposed_parent to a #{self.class.to_s} class, not a #{proposed_parent.class.to_s}" unless proposed_parent.is_a? self.class
      self.move_to_child_of(proposed_parent)
      inherit_from_parent!      
    end
end

def inherit_from_parent
  raise "No parent to inherit from" if self.root?
  self.account = self.parent.account    
end

def inherit_from_parent!
  inherit_from_parent
  save!
end

I don't know if it is as a result of the nested_set that you can't do something like the below which you can do in acts_as_tree or is the implementation in the plugin that forces you to create a root node first?

object = parent.children.new