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.

9.1.3 Using Paperclip<br />

Attaching a file<br />

When you run bin/cucumber features/creating_tickets.feature again, you’re<br />

told your model is missing one more thing:<br />

When I press "Create Ticket"<br />

Ticket model missing required attr_accessor<br />

for 'asset_file_name' (Paperclip::PaperclipError)<br />

attr_accessor references a Ruby method that defines a setter and a getter method<br />

named after its arguments, such as in the following listing.<br />

Listing 9.3 attr_accessor example<br />

attr_accessor :foo<br />

# is the same as...<br />

def foo<br />

@foo<br />

end<br />

def foo=(value)<br />

@foo = value<br />

end<br />

These getter and setter methods are defined automatically by Active Model for the<br />

fields in your database. Paperclip wants the asset_file_name method defined on<br />

your Ticket instance’s method. asset_file_name is one of four methods used by<br />

Paperclip to track details about the file. The other methods are asset_content_type,<br />

asset_file_size, and asset_updated_at. To define the asset_file_name method<br />

and its siblings, create a migration that adds them as attributes of the Ticket model by<br />

running this command:<br />

rails g paperclip ticket asset<br />

This paperclip generator (provided by the Paperclip gem) adds the proper fields to<br />

your tickets table. You tell it you want the attachment to be called asset.<br />

By running this command, you get a new file in db/migrate that ends with<br />

_add_attachment_asset_to_ticket.rb. If you open this file now, you should see a prefilled<br />

migration, as shown in the following listing.<br />

Listing 9.4 db/migrate/[time]_add_attachment_asset_to_ticket.rb<br />

class AddAttachmentAssetToTicket < ActiveRecord::Migration<br />

def self.up<br />

add_column :tickets, :asset_file_name, :string<br />

add_column :tickets, :asset_content_type, :string<br />

add_column :tickets, :asset_file_size, :integer<br />

add_column :tickets, :asset_updated_at, :datetime<br />

end<br />

def self.down<br />

remove_column :tickets, :asset_file_name<br />

remove_column :tickets, :asset_content_type<br />

217

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

Saved successfully!

Ooh no, something went wrong!