Rails upload files to AWS
There is a very easy way to upload files to AWS S3, however you can easily get lost with different gems and options available. My favorite way is using paperclip with aws-sdk. Here are some quick steps to get you started, look at the gems homepages for more information.
Gemfile
gem 'aws-sdk'
gem 'paperclip'Then run bundler
bundle installconfig/initializers/aws.rb
AWS.config({
:access_key_id => 'REPLACE_WITH_ACCESS_KEY_ID',
:secret_access_key => 'REPLACE_WITH_SECRET_ACCESS_KEY',
})Example of what your model might look like:
class User < ActiveRecord::Base
has_attached_file :photo,
:storage => :s3,
:bucket => 'mybucket',
:s3_credentials => {
:access_key_id => ENV['S3_KEY'],
:secret_access_key => ENV['S3_SECRET']
}
endMigration:
class AddPhotoColumnsToUser < ActiveRecord::Migration
def change
change_table :users do |t|
t.has_attached_file :photo
end
end
endNote: has_attached_file does not seem to work with create_table
This is how to put it in your form
<%= form.file_field :avatar %>You also need a create action in your controller. Assuming you used a scaffold, it should work just fine. Enjoy!



