Image uploading is an important feature in web application. Here are few steps to enable image uploading function using “Paperclip gem”:
                 gem 'paperclip'
          then run bundle install
                  
                rails generate migration add_image_to_users
Step-1:
         Paperclip requires the installation of ImageMagick on your Mac machine:
              brew install imagemagick
Step-2:
         Open gemfile and add gem:
Step-3:
         After adding gem add the image column in your table, here users table. Run 
         command:
         This will create new migration in db/migrate then run migration
Step-4:
         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/
Step-5:
         After that you need to edit in your users new form and edit form with following HTML code
            app/views/users/new.html.erb
            app/views/users/edit.html.erb   
               <div class="field">
                   <%= f.file_field :image %>
              </div>
Step-6:
         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
            <p>
              <strong>Image:</strong>
              <%= image_tag @user.image %>
            </p>
No comments:
Post a Comment