Florian Odronitz
2006-Jan-19  19:08 UTC
[Rails] Problem with an Tree-like object hierarchy (ActiveRecord acts_as_tree)
Hello people on rails,
I am developing a web interface for a database that has hierarchical  
data. I want the user to be able to browse the tree (~1300 nodes) and  
activate/deactivate and showing/hiding groups of nodes (like  
selecting one node selects all the children and the leafs). So I have  
a tree of objects (ActiveRecord acts_as_tree). Because I need the  
tree to be persistent and I don''t want to resend the whole thing  
after every change I use Ajax to update only the parts that changed.  
This all works like a charm! Sending a message (eg activation) down  
the tree (root->leafs)  is fine.
Now the problem: when I pick  an node from the tree and try to  
activate itself and all its ancestors, only the one element will get  
activated. Trying something like my_node.children[0].parent.active =  
true doesn''t work either. When I make the call recursive like
def show_up
     puts "activating #{self.name}"
    @active = true
     if parent then parent.show_up end
end
I can see in the log file that its traversing all the way up to the  
root, but only the activation of the node called will ''stick''.
speaking of ''stick'', to preserve the tree between requests I
store it
in the session variable and retrieve it from there:
   def unfreeze_taxtree
      if taxtree_frozen then return Marshal.load(session[:tax_tree])
      else return nil end
   end
   def freeze_taxtree(tax)
      return session[:tax_tree] = Marshal.dump(tax)
   end
   def get_tax_from_freezer(tax_id)
     @@tax_tree = unfreeze_taxtree
     ObjectSpace._id2ref(@@tax_tree.find_tax(tax_id))
   end
So tax are the nodes and tax_tree the ... well ... tree.
I did the marshaling and retrieving via object id because I was  
getting paranoid about the objects not being the original ones after  
unfreezing from the session cache.
Before the first freezing I tried to send down a ping from the root  
to all the twigs and back, to force the instantiation of all children  
and parents. No cure.
I thinks it boils down to: what is the difference between children  
and parents?
I would greatly appreciate any thoughts or help on this.
cheers, Florian
