Topic: HOWTO: Using Amazon S3 with Attachment_Fu on Rails

Using Amazon S3 with Attachment_Fu on Rails

If you're using the attachment_fu Rails plugin to upload files (eg images, video, etc...), you will probably be aware that there is a built-in storage option to use Amazon's Simple Storage Service (S3). The reason i opted to use S3 was that it would take some load of my own server, and i think in the long run it is more efficient than using the file system or db options. Many web startups are doing exactly the same thing.

So how do we implement it?

First create an Amazon Web Services account, and sign up to use S3:

Note that you will have to give some credit card details as the service is not free, but it is damn cheap!!

You will be given an access key id and a secret access key. These are both very long strings.

Next step is to create a bucket. A bucket is like a folder that will hold all your files. The easiest way to do this is get an S3 GUI, just like CocoaMSQL(Mac)/HeidiSQL(Win) for MySQL. There are a number of options to consider, eg:

S3 Browser:

Cockpit: … ckpit.html


As i am using a Macbook Pro, i opted to use the S3 Browser.

With the S3 Browser, you just need to create a New Connection by entering you access key id and secret access key. There will be a similar option for other S3 GUI's. Once you've done this you will be connected to your S3 storage and can simply add and delete buckets as you wish! I think it is a good idea to have a separate bucket for the development, test, and production versions of your app (just like you do with databases). With the S3 Browser you can also view the contents of your buckets and delete files from the buckets as well.

Next step is to install the S3 gem, eg:

sudo gem install aws-s3

Now get back to your app. I use attachment_fu for photos. So in my Photo model, i have the following:

has_attachment :content_type => :image, :storage => :s3, :size => 0.megabyte..3.megabytes, :resize_to => '450x450>', :thumbnails => { :thumb => '150x150>' }

Go to your Rails app config directory and you should see the amazon_s3.yml file.

Edit it as follows. Basically you need to enter your access key id and secret access key's plus specify the bucket names:

bucket_name: photos_myproject_development
access_key_id: xxxxxxx
secret_access_key: xxxxxxxxxxxx

bucket_name: photos_myproject_test
access_key_id: xxxxxx
secret_access_key: xxxxxxxxxxxx

bucket_name: photos_myproject_production
access_key_id: xxxxxx
secret_access_key: xxxxxxxxxxxx

I am using Subversion for source control, but i do not check the amazon_s3.yml file into Subversion, in fact i treat it just like database.yml (there are different ways of dealing with this, i won't be going into this right now).

That's it. Pretty easy. Upload your files and then use your S3 browser to see that they are indeed on S3!