Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Image upload using carrierwave in rails

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 467
    Comment on it

    Hi friends,

    Today I am going to tell you how we can upload images in rails using carrierwave gem. It automatically creates folder inside public folder and uploads images there. You can also customize the upload location. Here is the step-by-step process of how we can integrate it to our application:

     

    1. Added gem 'carrierwave'  to the Gemfile

    gem 'carrierwave'

    2. Run the bundle

    bundle install

    3. Generate an uploader using:

    rails generate uploader ProfilePic

     It generates a file app/uploaders/profile_pic_uploader.rb

    4. Add a field in the model where you want to store the uploaded image path

    rails g migration add_profile_pic_to_users profile_pic:string
        rake db:migrate

    5. Open your model file and mount the uploader:

    class User < ActiveRecord::Base
      mount_uploader :profile_pic, ProfilePicUploader
    end

    6. In the view file where you want to upload the profile pic add this:

    <tr>
      <td><%= f.label :profile_pic %></td>
      <td><%= f.file_field :profile_pic %></td>
    </tr>

    Now once you save the profile pic it will upload the image in public folder and also save the path of the image to profile_pic field of the user model.

    7. For storing thumbnail with image, you can configure it inside profile_pic_uploader.rb and uncomment the following section

    version :thumb do
      process :resize_to_fill => [50, 50]
    end

    8. To compress images you need to install imagemagic in your machine. You can do it by typing

    sudo apt-get install imagemagick

    9. For using image magick we are here installing the gem mini_magick. So add this to your Gemfile and run bundle

    gem 'mini_magick', '~> 4.3'
    

    10. Now uncomment the following line in your profile_pic_uploader.rb to include minimagic

    include CarrierWave::MiniMagick
    


    Thus you are now ready to upload images using carrierwave. Hope you liked it.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: