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
  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
  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:

12 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…

  2. Please help….I am getting error like undefined method `attr_accessible’ for # while uploading image…..

    1. did you get the answer of your question? If yes then please tell me the answer because i am also having the same issue.
      Thanks in advance

  3. thank you Ganesh Kunwar for this nice tutorial..
    add following codes in image.rb MODEL.
    validates_attachment_file_name :image, :matches => [/png\Z/, /jpe?g\Z/, /gif\Z/]

    and In controller add method
    def image_params

    adding this you may not mention attr_accessible :image in MODEL image.rb
    this will work in rails 4

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