File uploading through Paperclip in rails 3.x

File uploading through Paperclip in rails 3.x

2 Minutes Read

Rails3Paperclip is an easy file attachment library for Rails Applications. Attached files are saved to the file system, database or cloud and referenced in the browser by an easily understandable specification. Here is an example to explain the image attachment for a user profile in an application. This example narrates about saving the image in the file system. However, the images can be saved in S3 bucket [Amazon Simple Storage Service, S3] or database.



ImageMagick must be installed in the system and Paperclip must have access to it. ImageMagick is a software suite to create, edit, compose, or convert bitmap images. It can read and write images in a variety of formats. You can download it by visiting the following URL:

Include the paperclip gem in your Gemfile

gem "paperclip"

Then run the bundler to install the gem

bundle install

Add the fields for the image processing as below in your migration file

class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :name
t.string :photo_file_name
t.string :photo_content_type
t.string :photo_file_size

Then run your migration files

rake db:migrate


Modify the user model for cropping and save image in your system folder

has_attached_file :photo, :styles => { :small => "150x150>" },
:url => "/system/:attachment/:id/:style/:basename.:extension",
:path => ":rails_root/public/system/:attachment/:id/:style/:basename.:ex

Here you can specify the file path and the image size as per the requirement.

Modify your view file to upload an image

<pre class="plain plain">&lt;%= form_for :user,:url =&gt; {:action =&gt; "create"}, :html =&gt; { :multipart =&gt; true } do |f| %&gt;
&lt;%= f.file_field :photo %&gt;
&lt;% end %&gt;</pre>

Write the following code to display the image of a user

<%= image_tag (:small)%>

Please stay connected with us by subscribing our email.
Also feel free to share your opinions in the comments section below:

, ,
Jayadev Das

Do what you do best in – that’s what I’ve always believed in and that’s what I preach. Over the past 25+ years (yup that’s my expertise ‘n’ experience in the Information Technology domain), I’ve been consulting to small, medium and large companies ‘bout Web Technologies, Mobile Future as well as on the good-and-bad of tech. Blogger, International Business Advisor, Web Technology Expert, Sales Guru, Startup Mentor, Insurance Sales Portal Expert & a Tennis Player. And top of all – a complete family man!

No Comments

Post A Comment

Exit pop up

Sad to see you leaving early...

From "Aha" to "Oh shit" we are sharing everything on our journey.
Enter your email address to stay up to date with the latest news.
Holler Box