Upload files in Amazon S3 with Paperclip and Rails 4

Ishank Gupta

Here is a clean approach to set the configuration of model to upload images in Amazon S3 server with paperclip in Ruby on Rails. We need following gems in out Gemfile
gem 'paperclip'
gem 'aws-sdk'
In the config folder create a file called config/api_config.yml where you set up your bucket name, amazon access key and access secret in the file.
  amazon_bucket_name: demo-dev
  amazon_access_key: XXXXXXXXXXXXXXXXXXXX
  amazon_access_secret: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

  amazon_bucket_name: demo-prod
  amazon_access_key: XXXXXXXXXXXXXXXXXXXX
  amazon_access_secret: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Our next step is to create a file called config/paperclip_options.yml, which will contain configurations of paperclip like styles, url, convert_options, etc
common: &default_settings
  :access_key_id: <%= API_CONFIG['amazon_access_key'] %>
  :secret_access_key: <%= API_CONFIG['amazon_access_secret'] %>
  :bucket: <%= API_CONFIG['amazon_bucket_name'] %>

production: &production
      :storage: !ruby/symbol s3
      :s3_protocol: :http
        <<: *default_settings
        :avatar: :public_read
      :default_url: '/assets/missing.png'
        :mini: '48x48>'
      :url: ":s3_domain_url"
      :path: 'images/:id/:style/:basename.:extension'
        :all: '-strip -auto-orient -colorspace sRGB'

  <<: *production
This file will set s3_credentials to the credential in api_config.yml and will set up other asset details. Now create a file named config/initializers/paperclip_config.rb which will map the configuration of above two file and set those in the environment variables of the Ruby on Rails app.
API_CONFIG = YAML.load_file("#{Rails.root}/config/api_config.yml")[Rails.env]

class DemoApp::Configuration
  class << self
    attr_accessor :paperclip_options

DemoApp::Configuration.paperclip_options = YAML.load(ERB.new(File.read(Rails.root.join('config', 'paperclip_options.yml'))).result)[Rails.env]
Paperclip::Attachment.default_options[:use_timestamp] = false
In our user model, we just need to add the mapping of the image file, we can simply do it with DemoApp::Configuration.paperclip_options[:users][:image] which we have configured in paperclip_config.rb file.
class User < ActiveRecord::Base

  has_attached_file :image,

You can create view of your choice to upload the image. Just make sure image key in the params should have a image. You can have a look at Upload image without submitting form, works on all browsers to get an idea for the controller and view code.