Skip to content

Instantly share code, notes, and snippets.

@edomaru
Created June 27, 2015 22:36
Show Gist options
  • Save edomaru/134d9276c56406a81c71 to your computer and use it in GitHub Desktop.
Save edomaru/134d9276c56406a81c71 to your computer and use it in GitHub Desktop.
Rails - Upload File with Carrierwave

Upload File with Carrierwave

Installation

Add this gem in Gemfile:

gem "carrierwave", "0.10.0"
gem 'mini_magick', '~> 4.2.7'

How to use

  1. Generate uploader

    rails generate uploader Picture

  2. Add new field to the model

    rails generate migration add_picture_to_model picture:string

  3. Run The migration

    rake db:migrate

  4. Open the model to attach the uploader and add this line

    mount_uploader :picture, PictureUploader

  5. Add attribute to the form tag like so:

    form_for(@object, html: { multipart: true })

  6. Add file_field to the form element, like so:

    <%= f.file_field :picture, accept: "image/jpeg, image/png, image/gif" %>

  7. Open up uploader/picture_uploader.rb and uncomment these lines:

     ...
     include CarrierWave::MiniMagick
     process resize_to_fit: [600, 600]
    
     def extension_white_list
         %w(jpg jpeg gif png)
     end
     ...
  8. Permit the parameters in controller

    ...
     params.require(:object).permits(:picture)
    ...
    
  9. You may add validation for the picture both in server or in client. this is how to validate in server:

     ...
     validate :picture_size
    
     private
         def picture_size
             if picture.size > 5.megabytes
                 errors.add(:picture, "Should less than 5MB")
             end
         end
     ...

and this is how to validate file in client side:

<script type="javascript">
  $('#recipe_picture').bind('change', function () {
      size_in_megabytes = this.files[0].size/1024/1024;
      if (size_in_megabytes > 5) {
          alert('Maximum file size is 5MB. Please choose  a smaller file');
      };
  });
</script>
  1. To show the image in view:

<%= image_tag(object.picture.url) if object.picture? %>

  1. If you find errors like this:

    unitialized constant Object::PictureUploader

    Then you may add this line on app/config/environment.rb: require 'carrierwave/orm/activerecord'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment