Add this gem in Gemfile:
gem "carrierwave", "0.10.0"
gem 'mini_magick', '~> 4.2.7'
-
Generate uploader
rails generate uploader Picture
-
Add new field to the model
rails generate migration add_picture_to_model picture:string
-
Run The migration
rake db:migrate
-
Open the model to attach the uploader and add this line
mount_uploader :picture, PictureUploader
-
Add attribute to the form tag like so:
form_for(@object, html: { multipart: true })
-
Add
file_field
to the form element, like so:<%= f.file_field :picture, accept: "image/jpeg, image/png, image/gif" %>
-
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 ...
-
Permit the parameters in controller
... params.require(:object).permits(:picture) ...
-
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>
- To show the image in view:
<%= image_tag(object.picture.url) if object.picture? %>
-
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'