Photoupload in a Ruby on Rails application

A lot of Ruby on Rails web applications have to use photos (e.g. for user profiles) In the best case these photos can be already stored in several sizes or otherwise processed before being stored to different possible location. Also these photos have to be attache to a ruby on rails model like an user or an article.
1 answer

Photoupload in a Ruby on Rails application using paperclip

Implementing a custom solution for photo upload functionality can be very painful.

There is a very good ruby on rails gem which provides this functionality called paperclip.

Actually paperclip can handle all file uploads not only photos. But the following description focuses on the photos because it is the most common one.

Paperclip requires at least Ruby version 1.9.2 and Rails version 3.0.

It is mandatory to have an installation of ImageMagick before using paperclip. Keep in mind that you need a local installation as well as an installation on your production server.

ImageMagick can be downloaded here: http://www.imagemagick.org

Paperclip is a ruby gem. Therefore it is really easy to install it.
The following line has to be added to the gemfile of the Ruby on Rails project:
gem "paperclip", "~> 3.0"

Note: Make sure to upgrade to newer versions of paperclip once they are available by changing the version number in the gemfile.

After adding the paperclip to the gemfile, run bundle install to download the gem and add it to the Ruby on Rails application.

After installation you have to adjust your model (e.g. user):

class User < ActiveRecord::Base
attr_accessible :profilpic
has_attached_file :profilpic, :styles => { :thumbnail => "100x100>"}
end

This adds a profilpicture attribute to the user model and a custom size of 100x100 pixels.

Next step is to change the database schema to store the new attributes by running the command rails generate paperclip user profilpic

In a ruby on rails form view it is now possible to show on photoupload input:

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

Paperclip handles all the uploading and processing of the image.

Also the photo can be showed in a view:

<%= image_tag @user.profilpic.url %>

Taggings: