Hi,
Carrierwave gem provides a flexible way to upload files from our Ruby applications. It is similar to paperclip gem in Rails 2.
Installing Carrierwave
We can install carrierwave gem using the following command.
$ gem install carrierwave
In our Rails application open the Gemfile and add the line
$ vi Gemfile
gem 'carrierwave'
Using carrierwave
Example:
Create a Rails application where an candidate is applying for an job application.
$ rails new job_application $ cd job_application $ rails generate resource candidate name:string email:string phone:string skills:string qualification:string $ rake db:migrate
We are now going to provide the candidate with option to upload the resume.
$ rails generate uploader Resume
The above command will create a file resume_uploader.rb in app/uploaders/
In this file we can see something like below
resume_uploader.rb
class ResumeUploader < CarrierWave::Uploader::Base storage :file end
Add a string coloumn to the model where we want the uploader
t.string :resume
After adding this coloumn in migration drop and migrate the database.
Now mount the uploader in the model file.
class Candidate < ActiveRecord::Base mount_uploader :resume, ResumeUploader end
In the form dont forget to set the html mutipart option to true for uploading the resume.
Now everything is done. We can now upload the resume.
Screenshots:
——————————————————————————————————————————-
Restricting User to upload only specified types of files
There is one more interesting option is there in carrierwave. We can restrict the type of the file to be uploaded.
Open the file app/uploaders/resume_uploader.rb
def extension_white_list %w(doc docx pdf odt) end
We can provide the set of file types that can be uploaded. If the user tries to upload any file apart from what is provided in the extension white list method, then the carrierwave will not upload the file and it throws an error to the user.
Screenshot:
——————————————————————————————————————————-
The above is the simple example of how we can use carrierwave for uploading documents. I hope you found the above example useful for getting started and working with carrierwave.
For more information you can look at the following github documentation - https://github.com/jnicklas/carrierwave
Regards
Ramachandran




Hey , Thanks It was very helpful