27.02.2013 Views

Rails%203%20In%20Action

Rails%203%20In%20Action

Rails%203%20In%20Action

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

18 CHAPTER 1 Ruby on Rails, the framework<br />

In the beginning...<br />

In really early versions of Rails, you had to generate links like this:<br />

link_to "Back", { :controller => "purchases",<br />

:action => "show",<br />

:id => @purchase.id }<br />

This hash was then interpreted and matched to a route, like /purchases/1. You can<br />

still use it today in Rails 3 if you wish, but it’s not best practice. The hash can be<br />

shortened:<br />

link_to "Back", "/purchases/#{@purchase.id}"<br />

These days, the following is best:<br />

link_to "Back", @purchase<br />

By using the routing helpers introduced in Rails 2 and still available in Rails 3.1, you<br />

can have much shorter link_to calls in your application, increasing the readability<br />

of the code throughout.<br />

Let’s try filling in this form now, for example, by changing the cost from 100 to 10 and<br />

clicking Update Purchase. You now see the show page but with a different message,<br />

shown in figure 1.9.<br />

Clicking Update Purchase brought you back to the show page. How did that happen?<br />

Click the back button on your browser and view the source of this page, specifically<br />

the form tag and the tags directly underneath, shown in the following listing.<br />

Listing 1.14 The HTML source of app/views/purchases/edit.html.erb<br />

form action="/purchases/<br />

2" class="edit_purchase" id="edit_purchase_2" method="post"<br />

div style="margin:0;padding:0;display:inline"<br />

input name="_method" type="hidden" value="put" /<br />

/div<br />

...<br />

This form’s action points at /purchases/2, which is the route to the show action in<br />

PurchasesController. You should also note two other things. The method attribute of<br />

this form is a post, but there’s also the input tag underneath.<br />

The input tag passes through the _method parameter with the value set to "put".<br />

Rails catches this parameter and turns the request from a POST into a PUT. This is the<br />

Figure 1.9 Viewing an updated purchase

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!