Upload files using Paperclip on Ruby on Rails

Paperclip is an awesome plugin to handle file uploads in Ruby on Rails. I’ve been using in a couple of projects lately and I thought I’d talk a bit about it.

First of all, you need to install the plugin on your project by doing:

script/plugin install git://github.com/thoughtbot/paperclip.git

from your project main directory. After this, usage is very simple.

Let’s imagine I have a user model and I want to have a avatar attribute to include a picture of the user and let’s say we want that avatar to be resized to 3 different sizes (120×120, 48×48 and 26×26). Paperclip does this using ImageMagick.

We’re first going to create a migration to hold all this information:

class AddAttachmentsAvatarToUser < ActiveRecord::Migration
  def self.up
    add_column :users, :avatar_file_name, :string
    add_column :users, :avatar_content_type, :string
    add_column :users, :avatar_file_size, :integer
    add_column :users, :avatar_updated_at, :datetime
  end

  def self.down
    remove_column :users, :avatar_updated_at
    remove_column :users, :avatar_file_name
    remove_column :users, :avatar_content_type
    remove_column :users, :avatar_file_size
  end
end

Then we define the attribute in the model:


class User < ActiveRecord::Base
has_attached_file :avatar, :styles => { :large => "120x120>", :medium => "48x48>", :thumb => "26x26>" }
end

Here’s an example on how your form should be:

<% form_for :user, @user, :url => user_path, :html => { :multipart => true } do |form| %>
    <%= form.file_field :avatar %>
  <% end %>

Your controller doesn’t have to do anything specific to handle the avatar, just save the user as usual.

  def create
    @user = User.create( params[:user] )
  end

And finally, if you want to show the avatar in your view, here’s some examples:

  <%= image_tag @user.avatar.url %>
  <%= image_tag @user.avatar.url(:medium) %>
  <%= image_tag @user.avatar.url(:thumb) %>

That wasn’t very difficult. There’s some advance stuff you can do with Paperclip, like upload via a URL or upload your files to Amazon’s S3 or define post processing operations on your files.

So get creative and use it in your projects. :)

Update: The WebFellas have a very deep and interesting article about Paperclip, check it out.

picture-52



Other Entries

About

Reinventar is the home of Pedro Sousa, an entrepreneur and developer living in Lisbon, Portugal.

I co-founded Think Orange, created Book Worms and I'm also involved in the Ruby on Rails community and in the SHiFT organization.

I usually write here about design, web, technology, lifestyle and other random ideas.

Photos

new ambient lightsnew flipchartcowork lisboa entrancehole in the wall

Interesting

PROJECTS

Think Orange Book Worms SHiFT

Recommended Reading