Rails tutorial: Upload image with paperclip gem

Paperclip is intended as an easy file attachment library for Active Record. Paperclip is ruby gem which helps to upload image or attachment in rails application. We can upload attachment using paperclip gem in rails through following steps.

Add paperclip gem to your Gemfile

gem "paperclip"

Install gem (run on command prompt):

bundle install

Create controller (say Images):

rails g controller Images index new show

Which will generate images_controller.rb to app/controllers directory which contains index, new and show action and respective views to the app/views/images directory. It also add routes for all these 3 actions.

Create Image model (say Image):

rails g model Image

Create table (Image):
Use following code in db/migrate/xxxxxx_create_image.rb file.

def change
  create_table :images do |t|
    t.string :image_file_name
    t.string :image_content_type
    t.string :image_file_size
    t.datetime :image_updated_at

Migrate database:

rake db:migrate

Use following code to create form (in views/Images/new.html.erb)

<%= form_for(:image, :url => {:action => 'create'}, :html => {:multipart => true}) do |f| %>
  <%= f.file_field :image %>
  <%= f.submit "Upload" %>
<% end %>

Add new action to images controller called create. Configure routes for this action.

post 'images' => 'images#create'

Add following code to create action of images controller to upload image (in ‘create’ action of  controllers/images_controller.rb)

def create
  @image = Image.new(params[:image])
  if @image.save
    redirect_to :action => :show, :id => @image.id
    render 'new'

Adjust model:
Add following code in models/image.rb

attr_accessible :image
has_attached_file :image
validates_attachment_file_name :image, :matches => [/png\Z/, /jpe?g\Z/, /gif\Z/]

For the rails version >=4  we do not mention attr_accessible :image in MODEL image.rb. Instead of this we have to permit image parameters before create new image. For this add following method in images controller.

def image_params

And build image object as following in create action.

@image = Image.new(image_params)

Use following code to view uploaded image (in ‘show’ action of controllers/image_controller.rb)

@id = params[:id]
@image = Image.find(@id)

and add in (views/image/show.html.erb)

<%= image_tag @image.image.url %>

Start server and run on browser:


Important Note (Update on 14th May, 2018)

Now the paperclip gem is deprecating and no longer maintaining. For the new Rails version (~>5.2), Rails introduced ActiveStorage , so we can use ActiveStorage instead of Paperclip or similar gem to attach and upload file/attachment.


Leave a Reply

Your email address will not be published. Required fields are marked *

Enter Captcha Here : *

Reload Image