ActiveRecord
2006-Apr-12 19:54 UTC
[Rails] ActiveRecord Parent-Child relationship bug? config problem?
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 -- Posted via http://www.ruby-forum.com/.
Henry Turner
2006-Apr-12 23:12 UTC
[Rails] ActiveRecord Parent-Child relationship bug? config problem?
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 On 4/12/06, ActiveRecord <not_a_valid_email@noemail.com> wrote:> 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 > > -- > Posted via http://www.ruby-forum.com/. > _______________________________________________ > Rails mailing list > Rails@lists.rubyonrails.org > http://lists.rubyonrails.org/mailman/listinfo/rails >
ActiveRecord
2006-Apr-12 23:33 UTC
[Rails] Re: ActiveRecord Parent-Child relationship bug? config probl
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-- Posted via http://www.ruby-forum.com/.