27.02.2013 Views

Rails%203%20In%20Action

Rails%203%20In%20Action

Rails%203%20In%20Action

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

222 CHAPTER 9 File uploading<br />

asset field to use the assets method, because it’ll need to check the assets of a ticket<br />

rather than the asset. You also need to change the h3 that currently reads Attached<br />

File so it reads Attached Files because there’s more than one file. You should also<br />

change the div that encapsulates your assets to have the class attribute of assets.<br />

These three changes mean that you now have these three lines in app/views/tickets/<br />

show.html.erb:<br />

<br />

Attached Files<br />

<br />

When you call exists? this time, it calls the ActiveRecord::Base association method,<br />

which checks if there are any assets on a ticket and returns true if there are. Although<br />

assets isn’t yet defined, you can probably guess what you’re about to do.<br />

First, though, you need to change the lines underneath the ones you just changed<br />

to the following:<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

Here you switch to using the assets method and iterate through each element in the<br />

array, rendering the same output as you did when you had a single asset.<br />

All of these changes combined will help your scenario pass, which is a great thing.<br />

When you run this scenario again, the first file field step passes, but the second fails:<br />

And I attach the file "spec/fixtures/speed.txt" to "File #1"<br />

And I attach the file "spec/fixtures/spin.txt" to "File #2"<br />

cannot attach file, no file field with id, name,<br />

or label 'File #2' found (Capybara::ElementNotFound)<br />

You could add another field:<br />

<br />

<br />

<br />

<br />

But that’s a messy way of going about it. The best way to handle this problem is<br />

through an associated model, a has_many association, and by using nested attributes. To<br />

use nested attributes in the view, you use the fields_for helper. This helper defines<br />

the fields for an association’s records, as many as you like. Let’s remove the file field<br />

completely and replace it with this:<br />

<br />

<br />

<br />

B Number increment

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

Saved successfully!

Ooh no, something went wrong!