Acts_as_tree and before_save

We all know that acts_as_tree gives us ability to set up data in a
tree-like structure and use methods like ‘parent’, ‘children’ and so on.

Something I’m completely stuck on. Observe.

class Page < ActiveRecord::Base
acts_as_tree

def before_save
raise self.parent.to_yaml
end
end

Well, you’d think that it should show element’s parent element but for
some reason it’s always blank.

Why don’t I have access to parent element here? Parent method seems to
work just fine when I actually save the thing. So child_element =
element.children.create(blahblah) and child_element.parent gives me the
parent element as it suppose to.

What am I missing here?

Thanks.

def before_save
raise self.parent.to_yaml
end
end

Why don’t I have access to parent element here? Parent method seems to
work just fine when I actually save the thing. So child_element =
element.children.create(blahblah) and child_element.parent gives me the
parent element as it suppose to.

it doesn’t work, because raise makes it not work. raise is:

http://www.rubycentral.com/book/ref_m_kernel.html#Kernel.raise

it raises an exception; maybe you’re looking for render or some other
method, but if i’m getting your drift (maybe i’m missing it entirely)
raise is not what you’re looking for.

it doesn’t work, because raise makes it not work. raise is:

http://www.rubycentral.com/book/ref_m_kernel.html#Kernel.raise

it raises an exception; maybe you’re looking for render or some other
method, but if i’m getting your drift (maybe i’m missing it entirely)
raise is not what you’re looking for.

I know what raise does. Point is that at that stage it should error out
and show me contents of the parent element. In my case it’s always nil
because self.parent is nil, instead of being a Page object.

I know what raise does.

sorry 'bout that. didn’t mean to bring it along that way … :slight_smile:

and show me contents of the parent element. In my case it’s always nil
because self.parent is nil, instead of being a Page object.

…what happens if you do it in an after_save call? a small guess would
be it wouldn’t work on a before_save :on => create (whereas :on =>
update would work) because the new record doesn’t actually exist in the
db when the before_save is called. if i am correct, the child.parent
method actually goes to the db to check the parent_id column, and the
before_save is called before the actual writing to the db.

…?