Wednesday, November 1, 2017

Image upload using paperclip gem in rails5

Image uploading is an important feature in web application. Here are few steps to enable image uploading function using “Paperclip gem”:

         Paperclip requires the installation of ImageMagick on your Mac machine:
              brew install imagemagick

         Open gemfile and add gem:
                gem 'paperclip'
         then run bundle install
         After adding gem add the image column in your table, here users table. Run 
               rails generate migration add_image_to_users

         This will create new migration in db/migrate then run migration
         We also need to add validation for your image attribute. Add following code in your model                    'user.rb'

             has_attached_file :img, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png"

             validates_attachment_content_type :img, content_type: /\Aimage\/.*\z/

         After that you need to edit in your users new form and edit form with following HTML code


               <div class="field">
                   <%= f.file_field :image %>

         After submitting the form if you want to show the image you need to add following code to the  app/views/users/show.html.erb

              <%= image_tag @user.image %>

No comments:

Post a Comment