Paperclip
Paperclip recently made some changes making it more flexible.
Paperclip is a library for ActiveRecord used for file attachment. The most common use is for uploading images. It can optionally create thumbnails when you upload images. Paperclip requires ImageMagick for resizing images but it doesn’t require any Ruby libraries like RMagick or MiniMagick.
You can install paperclip as a gem or as a plugin. The paperclip gem needs right_aws, mocha, and shoulda.
gem install right_aws
gem install mocha
gem install thoughtbot-shoulda --source=http://gems.github.com
gem install thoughtbot-paperclip --source=http://gems.github.com
To install the plugin, run ./script/plugin install git://github.com/thoughtbot/paperclip.git
.
Let’s say you have a User model and you want to add an avatar. On the users table, you need to add avatar_file_name.
class CreateUsers < ActiveRecord::Migration def self.up create_table :users do |t| t.string :login t.string :avatar_file_name end end def self.down drop_table :users end end
On user.rb, add has_attached_file
class User < ActiveRecord::Base has_attached_file :avatar end
You just need to set avatar to an uploaded file and paperclip will handle the rest. On app/views/users/new.html.erb
<% form_for :user, @user, :url => users_path, :html => { :multipart => true } do |form| %> <%= form.text_field :login %> <br /> <%= form.file_field :avatar %> <br /> <%= submit_tag 'Save' %> <% end %>
:multipart => true is needed when uploading files. Then on app/controllers/users_controller.rb
def new @user = User.new end def create @user = User.create(params[:user]) end
@user.avatar.url will give you the url of the uploaded image. That’s all the code you need to use paperclip. There are more options for creating thumbnails, validating the model, and post-processing.
The uploaded files will be saved on RAILS_ROOT/public/system/:attachment/:id/:style/:basename.:extension. On my computer the file is saved on RAILS_ROOT/public/system/avatars/1/original/image.jpg.
As you can see, the default style is original. To add more ’styles’,
class User < ActiveRecord::Base has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "100x100>" } end
When you upload the image, paperclip will save the original image, and resize the image to medium and thumb. On RAILS_ROOT/public/system/avatars/2, you will see the directories original, medium and thumb.
To get the medium and thumb images, you will use @user.avatar.url(:medium) and @user.avatar.url(:thumb).
On the users table, you can also add avatar_content_type (string), avatar_file_size (integer), and avatar_updated_at (datetime). These fields will be populated by paperclip automatically.
I will discuss validation and other post-processing options on my next post.