8/20/2018 - 3:38 PM

Accessing Account Within Rails App

Accessing account buckets within a rails app

  • In your GEMFILE: gem 'aws-sdk-s3', '~> 1'
    • This only loads the necessary items for using Amazon S3!
    • bundle install
  • Create the following file: config/initializers/amazon.rb
    • Within this file, you will store the credentials of your account
    region: 'us-west-2',
    endpoint: ""
  • In config/secrets.yml, store the actual access id and secrets:
  secret: adfbndggdhd
  id: fdwets245hb3433
  • Now, if you go into bundle exec rails c, you can create a buckets, check existing buckets and their items ...

Accessing A Bucket

  • In your model, you can add the following code:
class ContentPage < ActiveRecord::Base

    # Code for obtaining images on AMAZON S3
    def self.get_files_from_s3
        s3 =
        bucket = s3.bucket(Rails.application.secrets.aws_bucket)
        file_array = []

        files_from_bucket = bucket.objects(prefix: 'uploads/fsi/content_image/image').each do |obj|
            file_array << obj.key if obj.key.include?("thumb_")


  • s3 = won't need to supply any credentials, they are done already in the initialization
  • To obtain an existing bucket, pass in the name of the bucket: s3.bucket(name)
  • If your bucket contains folders within folders and you want to get to a specific folder path, you can use the prefix and insert the path you would like to retrieve your pictures from.
  • bucket = s3.bucket(name), bucket.objects() will return an array of images stored in the bucket which you can now iterate over!