Forum: Ruby on Rails Adding children via small subform

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.
Doug B. (Guest)
on 2006-02-09 01:15
I've read AWDR and especially the part concerning adding child
line_items to an order.  Unfortunately I want to do my process in
reverse and in doing what I thought would work I get a null object error
when trying to append the children to the parent.

This is a _major_ stumbling block in my Rails use as almost every one of
my projects has needed this so its a pretty vital problem I need to
overcome.

My two tables:
Reviews -< Pictures
(Parent) -< (Child)

I have a form where you first add a Review and after clicking an Ajax
link it produces a sub-form ready for inputting the child pictures.
However, no matter whether I want just one child or a group of children
on the form I can't seem to get the Child objects to '<<' (append) to
the parent object.

In the book you collect your cart of 'children' (line_items) then append
these after creating an order.

My code is (in this instance I try it with just a single child):
@picture = Picture.new(params[:picture])
@review = Review.new(params[:review])
@review.pictures << @picture.pictures

I'm totally at a loss and I'm on hands and knees.  Please please help
me.  I want to go far with Rails and this is killing me.

Thank you for reading.
David M. (Guest)
on 2006-02-09 01:37
(Received via mailing list)
If I understand your problem correctly (and I'm not sure that I do, so
please excuse me if that's the case), you shouldn't need to be
appending your 'children' to the parent in that fashion.

Try instead doing something like
@review = Review.new(params[:review])
@review.save
@picture = Picture.new(params[:picture])
@picture.review_id = @review.id
@picture.save

That will give you a new 'review' record, plus a new 'picture' record
with the review_id field in the 'picture' record pointing to the
'review' record.

There may be a more elegant way of achieving the same thing, but
hopefully this is clear enough and addresses the issue you're seeing.

Regards

Dave M.
This topic is locked and can not be replied to.