Forum: Ruby on Rails ActiveRecord Parent-Child relationship bug? config problem?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
C2cb8f8da4fce8e7308cd921b8b54bd8?d=identicon&s=25 ActiveRecord (Guest)
on 2006-04-12 21:54
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
6cf8286fcab5843f468d62f5e6fb22de?d=identicon&s=25 Henry Turner (Guest)
on 2006-04-13 01:13
(Received via mailing list)
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 #=> #<Parent>

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

cheers
-h
C2cb8f8da4fce8e7308cd921b8b54bd8?d=identicon&s=25 ActiveRecord (Guest)
on 2006-04-13 01:33
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 Turner 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 #=> #<Parent>
>
> Until your child is saved @c.parent_id will be nil so your poor child
> wont know where to look!
>
> cheers
> -h
This topic is locked and can not be replied to.