I'm implementing a heap data structure in Rails, so I've got basically a binary tree, with nodes that have id, name, and parent_id.
I've noticed a really strange error when I try to "bubble up" one of my nodes. Here's what's up.
node = Item.find(266)
node.children.size
=> 0
node.swap_up
node.children.size
=> 0
node = Item.find(266)
node.children.size
=> 2
The behavior I'm expecting to see is that after I swap_up the node, it should have 2 children (as a result of bubbling up one level in the tree). But somehow the value of 0 "persists" until I "re-get" the node from ActiveRecord.
Here's the relevant definition from my model/item.rb
belongs_to :parent, :class_name => 'Item'
has_many :children, :class_name => 'Item', :foreign_key => 'parent_id'
This is causing all kinds of insane behavior in my heap implementation. Is there any way I can ensure that a node's children are "updated" when methods are called that affect it? (Or that more accurately, that affect the parent_id of other nodes to start pointing to it?)
Any help you guys might have would be invaluable. Thanks!
Here is a suggestion that may help.
This retrives item from db
node = Item.find(266)
node.children.size
=> 0
This uses cached item
node.swap_up
node.children.size
=> 0
I believe you can get rid of the cached copy and force it to go back to the db by doing this
node.swap_up
node.children(true).size
# should get => 2
instead of having to query the db again.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With