Upload image using paperclip in Rails

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

  1. Include the gem in your Gemfile:
    gem "paperclip"
  2. Install gem (run on command prompt):
    bundle install
  3. Create controller (say Image ):
    rails g controller Images index new show
  4. Create model (say Image):
    rails g model Image
  5. 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
    t.timestamps
    end
    end
  6. Migrate database:
    rake db:migrate
  7. 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 %>
  8. Use following code to Upload image (in ‘create’ action of  controllers/image_controller.rb)
    @image = Image.new(params[:image])
    if @image.save
    redirect_to :action => :show, :id => @image.id
    end
  9. Adjust model:
    Add following code in models/image.rb
    attr_accessible :image
    has_attached_file :image
  10. 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 %>
  11. Start server and run on browser:
    localhost:3000/images/new
About these ads

6 thoughts on “Upload image using paperclip in Rails

  1. Nice post. Can you please tell me how to change file upload directory when we use paperclip gem for file uploading…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s