We all must have got requirement for uploading files to Google Cloud Storage in our Rails Project for several purposes. Simplest way to do that is by using carrierwave. But the carrierwave gem uses Fog to upload files to google cloud storage. But now we’ve a gem called Carrierwave Google Storage, which uses the official google-cloud
gem by Google for Google Cloud Storage, instead of Fog.
Lets start integrating file upload using Carrierwave Google Storage step by step:-
1: Add carrierwave-google-storage
gem to your Gemfile
1 | gem 'carrierwave-google-storage' |
2: Create carrierwave.rb
to your config/inititalizers
1 | CarrierWave.configure do |config| |
3: Run following command to create uploader at app/uploaders/avatar_uploader.rb
1 | rails generate uploader Avatar |
This will generate following file
1 | class AvatarUploader < CarrierWave::Uploader::Base |
4: Add a string
field to your model to mount the uploader by running following migration
1 | rails g migration add_`string_field_name`_to_`your_model` `string_field_name`:string |
5: Now open your model file and mount the uploader to newly added string field
1 | class User < ActiveRecord::Base |
6: Now just save the file in model in following manner
1 | # If from api params |
7: To access uploaded file’s url, use following method
1 | user.avatar.url # This will give you the URL of the uploaded file |
References:-
Some good reads you may like:-
p.s. Nayan is a platform that offers high precision services for traffic monitoring and road safety. Check out our website