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.

220 CHAPTER 9 File uploading<br />

This file tells Git which files you don’t want versioned. The whole file should look like<br />

this now:<br />

.bundle<br />

db/*.sqlite3<br />

log/*.log<br />

tmp/**/*<br />

public/system<br />

By default, the .bundle directory (for Bundler’s configuration), the SQLite3 databases,<br />

the logs for the application, and any files in tmp are ignored. With public/system<br />

added, this directory is now ignored by Git too. You should also remove this<br />

directory from your latest commit, and thankfully, Git provides a way to do so by using<br />

these two commands:<br />

git rm public/system/assets/1/original/speed.txt<br />

git commit --amend -m "Added the ability to attach a file to a ticket"<br />

The first command removes the file from the filesystem and tells Git to remove it from<br />

the repository. The second command amends your latest commit to exclude this file,<br />

and it will be as if your first commit with this message never existed. Let’s push this<br />

change:<br />

git push<br />

Great! Now you can attach a file to a ticket. There’s still some work to do, however.<br />

What would happen if somebody wanted to add more than one file to a ticket? Let’s<br />

take a look at how to do that.<br />

9.2 Attaching many files<br />

You have an interface for attaching a single file to a ticket but no way for a user to<br />

attach more than one. Let’s imagine your pretend client asked you to boost the number<br />

of file-input fields on this page to three.<br />

If you’re going to add these three file-input fields to your view, you need some<br />

more fields in your database to handle them. You could define four fields for each fileupload<br />

field, but a much better way to handle this is to add another model.<br />

Creating another model gives you the advantage of being able to scale it to not just<br />

three file-input fields but more if you ever need them. Call this model Asset, after the<br />

name you gave to the has_attached_file in the Ticket model.<br />

When you’re done with this feature, you should see three fileupload<br />

fields as shown in figure 9.1.<br />

You can create new instances of this model through the ticket<br />

form by using nested attributes. Nested attributes have been a feature<br />

of Rails since version 2.3, and they allow the attributes of an associ-<br />

ation to be passed from the creation or update of a particular<br />

resource. In this case, you’ll be passing nested attributes for new<br />

Figure 9.1<br />

File-upload boxes

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

Saved successfully!

Ooh no, something went wrong!