Hooking Up My Rails App with Amazon s3 Using Paperclip
For quite some time I have been meaning to figure out how to get my static content onto Amazon s3. Using the heroku help here it wasn’t too bad at all! This is how I did it:
First go to Amazon’s AWS page here and sign up for s3. You then need to create a bucket, and it needs to be unique across the whole of Amazons site. As you can see, my bucket is called media.domainsby.me. It does not need to be reliant on a domain name, but I figured there would be a good shot it was unique.
Next I added the gems ‘paperclip’ and ‘aws-s3’ to my Gemfile and ran bundle install.
Then I modified my model to reflect the storage place for my application. If you notice, I am naming the image that I am uploading “background” and I am referencing a s3.yml file that has my credentials.
//This is my model
class User < ActiveRecord::Base
has_attached_file :background,
:storage => :s3,
:s3_credentials => "#{RAILS_ROOT}/config/s3.yml",
:path => "/:style/:filename"
end
After you add this to the model, you need to run a migration in order to tell you application information about the image. If you are using heroku, you still need to run this migration. I forgot this step at first and while I was able to save images - my application did not know the names of those files.
class AddBackgroundToUser < ActiveRecord::Migration
def self.up
add_column :users, :background_file_name, :string
add_column :users, :background_content_type, :string
add_column :users, :background_file_size, :integer
end
def self.down
remove_column :users, :background_file_name
remove_column :users, :background_content_type
remove_column :users, :background_file_size
end
end
Then Run:
rake db:migrate
Now add the s3.yml file under config/s3.yml
//here is the s3.yml file
development:
bucket: media.domainsby.me
access_key_id: ACCESS_KEY
secret_access_key: SECRET_ACCESS_KEY
test:
bucket: media.domainsby.me
access_key_id: ACCESS_KEY
secret_access_key: SECRET_ACCESS_KEY
production:
bucket: media.domainsby.me
access_key_id: ACCESS_KEY
secret_access_key: SECRET_ACCESS_KEY
Then finally, I put in the necessary information to both save and retrieve images - On my form I put this code for uploading images on the site:
<%= form_for @user, :html => { :multipart => true } do |f| %>
<%= f.file_field :background, :class => "inputshome" %>
<% end %>
And then in my show view in order to retrieve the image from Amazon
<%= image_tag @user.background.url %>
Its that easy! If you are having trouble, jump into your console and make sure that the User model knows where the image is e.g. run User.last.background.url and see if it returns anything. In order to test if the image is being saved correctly, you can log into your amazon account and check if it is there.
Let me know if you have any questions!