ActiveRecord Parent-Child relationship bug? config problem?


#1

If i have a parent that has_many :children, and the child belongs_to
:parent. Then when I add a new child to the parent like so:
parent.children << Child.new, then shouldn’t the child also have a
reference to the parent? but it doesn’t-- child.parent is nil-- what’s
going on here? is this as it should be-- shouldn’t it have a reference
to the parent. am i missing some config somehwere?

thanks for the help!
(couldn’t figure it out from the rdocs or the source-- not quite at that
level yet)

-mrspeck


#2

Hi mrspeck,

I’m surprised child.parent did not give you an error.

try…
@p = Parent.new
@c = Child.new
@p.children << @c
@c.parent #=> nil

but now do…

@p.save

and now…

@c.parent #=> #

Until your child is saved @c.parent_id will be nil so your poor child
wont know where to look!

cheers
-h


#3

Hey Henry-- thanks for the reply!

I understand that @c.parent will produce nil until @p is saved, but I
guess what I’m asking is if this is as it should be?

If you add a child to a parent, why wouldn’t the << method also go ahead
and point the child to the parent? (assuming the child belongs_to the
parent, and most defintely if the parent’s has_many :dependent=>true)
Doesn’t it just make sense then? I can’t think of a case where you
wouldn’t want this behavior, can you?

-mrspeck

Henry T. wrote:

Hi mrspeck,

I’m surprised child.parent did not give you an error.

try…
@p = Parent.new
@c = Child.new
@p.children << @c
@c.parent #=> nil

but now do…

@p.save

and now…

@c.parent #=> #

Until your child is saved @c.parent_id will be nil so your poor child
wont know where to look!

cheers
-h