Upload Image To S3 Using Carrierwave on Rails

This post is part of Awesome Gem series.


1. Add gem carrierwave

Carrierwave is gem provides a simple and extremly flexibale way to upload files from Ruby application. 

gem 'carrierwave'

gem 'fog' # Support storing file in AWS

2. Generate an uploader

rails generate uploader CoverImage 

  this should give you a file in:


3. Configure in uploader

It should something like this:

class CoverImageUploader < CarrierWave::Uploader::Base

  storage :fog


  def store_dir

  def extension_white_list
    %w(jpg jpeg gif png)


4. Mount the uploader in model (ActiveRecord)

class Post < ActiveRecord::Base
  mount_uploader :cover_image, CoverImageUploader


5. Configure to upload file to S3

We use the 'fog' gem which supports storing file in AWS, Google, Local and Rackspace. 


Create an initializer for this: 


You need to configure some options like this:

CarrierWave.configure do |config|
  config.fog_credentials = {
    provider: 'AWS',
    aws_access_key_id: ENV['AWS_KEY'],
    aws_secret_access_key: ENV['AWS_SECRET_KEY'],
    region: 'ap-southeast-1'
  config.fog_directory = ENV['S3_BUCKET_NAME']

region : should be one of [ 'eu-west-1', 'us-east-1', 'ap-southeast-1', 'us-west-1', 'ap-northeast-1' ]

fog_directory : Bucket Name in S3


6. Reference