Uploading files in a Rails App is no sweet job now a days. Out of all the gems available in Rails Ecosystem, “CarrierWave” is widely used for its easy integration and flexibility to upload files.
Benefits
- File Caching: Prevents users to select the file again & re-upload if the form fails the validation process
- Clean Code: Helps to write all the logic in uploader classes rather than in models, keeping your model clean and readable
- Image Processing: Provides efficient way to resize & crop images to different formats
- Storage Support: Stores files in third party storages such as AWS S3 bucket, Racksapce or Google Cloud
- Mongodb: Has good support for mongodb with the help of “carrierwave-mongoid” gem
Setting Up CarrierWave
Step 1:
In your Rails App, add the following to your gem file & run the bundle installation.
1 | gem 'carrierwave' |
Step 2:
Generate the uploader by running the following command:
1 | rails generate uploader Avatar |
It gives you a file in the path given below:
1 | app/uploaders/avatar_uploader.rb |
Here, “Avatar” is the column name.
Step 3:
Create a column to your model where you want to store the image:
1 2 | rails g migration add_avatar_to_students avatar:string Rakedb:migrate |
Step 4:
Open up the model and mount the uploader:
1 2 3 | class Student < ActiveRecord::Base mount_uploader:avatar, AvatarUploader end |
Step 5:
In the generated uploader file you can mention different versions of an image, just like this:
1 2 3 4 5 6 | version :thumb do process :resize_to_fill => [150, 150] end version :tiny_thumb do process :resize_to_fill => [50, 50] end |
Step 6:
Set file storage path in the uploader file. It’s the default storage path where all the files will be stored by CarrierWave.
1 2 3 | def store_dir "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}" end |
Step 7:
Navigate to config > initializers and create a file: carrier_wave.rb.
Paste the following code:
1 | require 'carrierwave/orm/activerecord' |
At this point, it loads CarrierWave after loading ActiveRecord.
You can also store the files into AWS S3 bucket by configuring in this way:
1 2 3 4 5 6 7 8 9 | CarrierWave.configure do |config| config.fog_credentials = { :provider => 'AWS', : aws_access_key_id => "YOUR AMAZON ACCESS KEY", :aws_secret_access_key => "YOUR AMAZON SECRET KEY", :region => 'us-west-1' # Change this for different AWS region. Default is 'us-east-1' } config.fog_directory = "bucket-name" end |
Now, you should be able to upload files on the fly after reading this article.
Wrapping Up!
Faced any hiccups while uploading a file using CarrierWave? Write to me at info@andolasoft.com and I’ll try to find a way.
Also, I would appreciate if you leave your feedback/suggestions below.