Ruby on Rails 3.2.11 : Using S3 as Paperclip’s Storage

Actually, this post was intended as a self note for me. So, it will be easier for me to set things up. Well, this story came up when I have a need of S3 for collecting my static files and user uploaded files, then I started my searching. I assume you already have your storage at S3, so I don’t need to explain how to setup a storage at S3 anymore. These are the steps that I did :

  1. Add these 3 gems to your Gemfile
    gem "paperclip", '~> 3.0'
    gem "aws-sdk"
    gem "aws-s3"
  2. Add a file named s3.yml (you can name it whatever you want, but I prefer to use s3) and place it inside config folder. You can see the content of the file below
    development:
      bucket: YOUR_DEVELOPMENT_BUCKET_NAME
      access_key_id: YOUR_ACCESS_KEY
      secret_access_key: YOUR_SECRET_ACCESS_KEY
    test:
      bucket: YOUR_TEST_BUCKET_NAME
      access_key_id: YOUR_ACCESS_KEY
      secret_access_key: YOUR_SECRET_ACCESS_KEY
    production:
      bucket: YOUR_PRODUCTION_BUCKET_NAME
      access_key_id: YOUR_ACCESS_KEY
      secret_access_key: YOUR_SECRET_ACCESS_KEY
  3. You’ve finished for S3 configuration part, now let’s start with the paperclip stuff. I assume you’ve made the migration file for a model you wish, let’s say the model is user. For example, this is the configuration that you need to add at your user model file
    has_mongoid_attached_file :avatar,
      :styles => {
        :small => "100x100>",
        :thumb => "200x200#",
        :large  => "500x500>" },
      :storage => :s3,
      :url            => ':s3_alias_url',
      :s3_host_alias  => 'yoursite.s3-website-ap-southeast-1.amazonaws.com', #this value depends on your bucket host alias, which is defined at S3 setup at AWS
      :s3_credentials => File.join(Rails.root, 'config', 's3.yml'), #this value depends on the file name that you made at the config file
      :path => "/avatars/:style/:id_:filename"

That’s it! Now run your web app and try uploading something to your model and see your bucket after that. I believe the file will be in the bucket.

Happy coding and cheers!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s