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.

Using JavaScript<br />

And I follow "Add another file"<br />

no link with title, id or text 'Add another file' found<br />

Before you fix it, however, let’s make the form render only a single asset field by<br />

changing this line in the new action in TicketsController<br />

3.times { @ticket.assets.build }<br />

to this:<br />

@ticket.assets.build<br />

By building only one asset to begin with, you show users that they may upload a file. By<br />

providing the link to Add Another File, you show them that they may upload more<br />

than one if they please. This is the best UI solution because you’re not presenting the<br />

user with fields they may not use.<br />

Now it’s time to make the Add Another File link exist and do something useful!<br />

9.4.2 Introducing jQuery<br />

The Add Another File link, when clicked, triggers an asynchronous call to an action,<br />

which renders a second file field.<br />

For the Add Another File link to perform an asynchronous request when it’s<br />

clicked, you can use the JavaScript framework called jQuery. In earlier versions of<br />

Rails, a JavaScript framework called Prototype came with it, but a large portion of the<br />

community prefers jQuery to Prototype. Developers can choose whether to use Prototype<br />

or jQuery or any other kind of JavaScript framework, but we use jQuery here<br />

because it’s favored in the community. 7<br />

To install jQuery in earlier versions of Rails, you would have had to go to http://<br />

jquery.com, download the latest version of jQuery, put it in your public/javascripts, and<br />

then include it in your application layout. Next, you would have had to install the<br />

jquery-rails gem. It was quite a lot of work for something that should have been<br />

simple!<br />

With Rails 3.1, you don’t need to download jQuery from the website or alter the<br />

default application in any way. With jquery-rails in the application’s Gemfile, you<br />

are already set up.<br />

Next, tell your application to include the JavaScript files from this gem if Rails hasn’t<br />

done it already. Currently, you have this line in your app/views/layouts/application<br />

.html.erb file:<br />

<br />

It generates HTML like this:<br />

<br />

<br />

7 Our choice totally has nothing to do with the fact that one of the authors is on the jQuery Core Team! We<br />

promise!<br />

233

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

Saved successfully!

Ooh no, something went wrong!