11.2. Uploading Files to Rails

To demonstrate some graphics features, I'm going to show you how to give a user the ability to upload a picture of their soup recipe, and then show you how to manipulate those images for some simple effects. Although you could roll this up yourself, I'm going to recommend the use of the attachment_fu plugin, which offers nice features for managing image metadata, automatic thumbnail generation, and validation of image parameters.

The plugin is available via the usual mechanism:

script/plugin install http://svn.techno-weenie.net/projects/plugins/attachment_fu/

To upload via attachment_fu, you need to align a data model, a controller, and a view. Once the file is uploaded, you'll need to change other views to display the image within the page. The attachment-fu plugin has specific expectations for the way the data is saved in your Rails application. In the Soups OnLine project, you can either include the image data columns within the recipe table or create a separate model and table to manage the metadata. On the theory that different things should be stored in different places, I'm opting for the separate table, which means you need the following model and migration:

$ script/generate model soup_image --svn

For what it's worth, I chose the name soup_image rather than just image on the vague theory that image is the sort of generic model name that is highly likely to have a nasty name collision somewhere down the road. It's unlikely that there's another ...

Get Professional Ruby on Rails™ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.