I am following the examples in the Agile Web Development with Rails
book and there is one thing that I dont quite understand.
Now after going through the example and getting everything working I
skimmed over it one more time and wondered if things would work if I
never created the partial for the cart. So I substituted the code
within the _cart.rhtml file into the "cart" div tag in the main rhtml
file and it worked.
What I don't understand is what is happening in the rjs file.
page[:cart].replace_html :partial => "cart", :object => @cart
When I got everything working after making the changes I thought that I
should be able to remove the :partial => cart section of the code
above, since the code that previously existed within the partial file
was moved to the store.rhtml file so there is no partial that is
allowing the cart to be displayed. Now for some reason it is at this
point that it blows up and throws the errors on to the screen.
The point of using AJAX here is that instead of refreshing the entire
page when you add something to your cart, you can just update the part
of the page that displays the shopping cart. The RJS line above is
saying "find the div called 'cart' in the current page, and replace it
with the contents of the partial template called 'cart'".
That's why you have the 'shopping cart' bit of RHTML in a separate file
called _cart.rhtml. It's so that you can reference *just* that bit of
HTML. If you lump the shopping cart HTML in with the overall page, how
will you tell Rails which bit of RHTML you want to re-render?
It sounds like you were expecting 'replace_html' to look through your
main RHTML file, and pull out the code that was originally rendered
inside the 'cart' div, and re-render that. I'm afraid it's not that
When you call 'replace_html', all it's doing is rendering some RHTML in
specified part of the current page with the newly rendered RHTML. You
could tell it to render a completely different partial template if you
wanted, or you could tell it just to render some text. That's why you
have to specify a partial template in this case -- if you didn't, it
would have no way of knowing what you're expecting it to render.