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.

240 CHAPTER 9 File uploading<br />

This is a little more verbose than the CoffeeScript and another great demonstration<br />

of how CoffeeScript allows you to write more with less. For more information and<br />

usage examples of CoffeeScript, see the CoffeeScript site: http://coffeescript.org.<br />

Let’s now give your link the id attribute that’s required to get this working so we<br />

can move on.<br />

PASSING THROUGH A NUMBER<br />

Open your app/views/tickets/_form.html.erb and replace the code for your Add<br />

Another File link with this:<br />

"add_another_file" %><br />

This gives the element the id attribute you require. Let’s witness this JavaScript in<br />

action now by running rails server to start up a server, signing in using the email<br />

address user@ticketee.com and the password password, and then creating a ticket on a<br />

project. Clicking the Add Another File link results in an error that you’ll fix shortly.<br />

Click it anyway. Afterward, go back to the window where rails server is running.<br />

This window shows information such as queries and results for every request, but<br />

you’re only interested in the last request made. This request should begin with the following<br />

line:<br />

Started GET "/files/new?number=1...<br />

This line tells you that Rails has begun serving a GET request to the /files/new route<br />

with a bunch of URL parameters. Your number parameter is the first one in this example.<br />

The following lines show the URL that was requested as well as what action and<br />

controller served this request:<br />

Started GET "/files/new?number=1" for 127.0.0.1 at [timestamps]<br />

Processing by FilesController#new as */*<br />

Parameters: {"number"=>"1"}<br />

The line you’re most interested in is the third line:<br />

Parameters: {"number"=>"1", ... }<br />

This is the params hash output in a semi-human-readable format. Here you can see it<br />

has the number parameter, so you can use this inside the new action. With all this in<br />

mind, you can change how you render the partial in the new action inside Files-<br />

Controller to this:<br />

render :partial => "files/form",<br />

:locals => { :number => params[:number].to_i,<br />

:asset => asset }<br />

You must convert the number parameter to an integer using the to_i method because<br />

it’ll be a String when it comes from params. It needs to be a Fixnum so the partial can<br />

add 1 to it.

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

Saved successfully!

Ooh no, something went wrong!