I am studying the ruby on rails guides namely, the “layouts and rendering” topic at http://guides.rubyonrails.org/layouts_and_rendering.html
I am confused about passing an instance variable to a redirect_to method. How is this possible? I thought redirect_to would be relevant for redirecting to another webpage or a url.
In the examples given on the guide it says the following:
2.2.2 Rendering an Action’s View
If you want to render the view that corresponds to a different action
within the same template, you can use render with the name of the
view:def update @book = Book.find(params[:id]) if @book.update_attributes(params[:book]) redirect_to(@book) else render "edit" end end
The render “edit” makes complete sense, its going to render that new form again. But what in the world is going on with redirect_to(@book)? What exactly is that going to render and how is a book object going to be redirected to? BTW, the book model has columns, Name, author, pages etc…
redirect_to documentation
So when one does
redirect_to(@book)@bookis a specific record with anid.Thus, the associated records (in this case @book) show method is used as a template.
In addition to above, if you look at the
routes.rbfile which defines these paths you will noticeNow this route is essentially translated as (you can see by running
rake routes)Notice the
book GET /books/:id books#show– which gets matched when you doredirect_to(@book)