Rails 4.2 Paperclip S3 Tutorial

Getting Paperclip to work on Rails 4.2 while storing files on AWS S3 takes some work on the AWS side, as well as in your app.  Here’s how to do it.

First, prepare S3.

In AWS, go to IAM to create a new user.

ScreenHunter_124 Dec. 13 09.59.jpg

You want to create a user just for your app as opposed to using the master keys for your account so you can limit the access in case someone gets your keys from your app.

Create a new user and enter a name:

ScreenHunter_126 Dec. 13 10.02

After you create the user, you will get this screen.  You will need these keys later, so click the button to download credentials.  Put them somewhere safe because you may need them in the future, too.

ScreenHunter_126 Dec. 13 10.03

Go back to the users view and click on the user

ScreenHunter_126 Dec. 13 10.06

Copy the User ARN value

ScreenHunter_126 Dec. 13 10.07.jpg

Now go to S3.  Create a bucket and note the region you are using.

ScreenHunter_126 Dec. 13 10.09.jpg

Go to the Properties of your Bucket, and click “Add bucket policy”:

ScreenHunter_126 Dec. 13 10.10

Update this code for your User ARN and your bucket name

{
“Version”: “2012-10-17”,
“Statement”: [
{
“Sid”: “”,
“Effect”: “Allow”,
“Principal”: {
“AWS”: “your-user-arn”
},
“Action”: “s3:*”,
“Resource”: [
“arn:aws:s3:::your-bucket-name”,
“arn:aws:s3:::your-bucket-name/*”
]
}
]
}

and paste it in your bucket policy (and save):

ScreenHunter_126 Dec. 13 10.14.jpg

AWS is now set-up.  It’s time to make the changes to your app.

Install the gems in your gemfile:

gem paperclip
gem ‘aws-sdk’

Adjust your models per the examples in Paperclip’s documentation.

Create a s3.yml file in the config folder (you may also want to add this to your .gitignore file to limit the exposure of your keys).  Put your keys from the user there:

development:
access_key_id: “your-access-key”
secret_access_key: “your-secret-access-key”

production:
access_key_id: “your-access-key”
secret_access_key: “your-secret-access-key”

in environments, change the development.rb and production.rb files:

config.paperclip_defaults = {
:storage => :s3,
:bucket => ‘your-bucket-name’,
:region => ‘your-region’
}

Your region name is not the same as the region you put here.  Find your region here.  If your bucket is not in the US, you may have to do additional settings.

Adjust your model:

has_attached_file :image,
:storage => :s3,
:s3_credentials => “#{Rails.root.to_s}/config/s3.yml”,
:s3_protocol => ‘https’,
:url =>’:s3_domain_url’,
:path => ‘/:class/:attachment/:id_partition/:style/:filename’
styles: {
medium: “300×300>”,
thumb: “100×100>” },
default_url: “/images/:style/missing.png”

To show the image in a view:

<%= image_tag @user.image.url(:thumb) %>