I’ve been through the construction of the depot application in the 1st edition of the book and have followed along in the 2nd to catch up on new concepts and techniques introduced in the 2nd version.
One thing I’m having a problem with (and wrapping my head around) is exactly how to deal with the linking of database tables and ROR models via foreign keys.
This may be a good addition to the book (i.e. a brain dead simple example of how to link up foreign key linked tables)
In my case, I have:
Book has_many :reviews
Review belongs_to :books
(I’m leaving out for now that each Review has_one Book)
I’ve created the book_id column for storing the foreign key in the DB. Now what I’m trying to do is create a link from the list of books that allows me to create a review for the given book (and automatically uses the id of the book as the foreign key for the row created in the DB to store the review). It seems like it should be easy and should occur nearly by magic, but I am missing something.
I pass the id of the book to the controller…
<%= button_to “Add Review”, :action => :add_review, :id => book.id %>
and then it gets hazy…
p((. # have to create the Review object in memory to receive input from the form…
p((. @review = Review.new
p((. # have to populate the Review object with input from the form…
p((. @review = Review.new(params[:review])
p((. if @review.save
p((. redirect_to :action => ‘index’
p((. render :action => :add_review
And that’s where it falls apart. The review is saved to the DB but it is orphaned (without a book_id).
I’m sure it’s something simple that I’m missing, but I don’t (yet) have the grasp of how to build things in ROR to fix it.
I’ll keep reading…