Felix
Felix

Reputation: 5619

rails AWS S3 delete file

I do uploads to amazon S3 with carrierwave that works fine.

But Now I want to add a delete function I tried this:

AWS::S3::S3Object.delete(@vid.video, 'bucket')

I got this error:

uninitialized constant MoviesController::AWS

The reason is clear .. But how do I set the AWS constant correctly and where?

config/initializers/carrierwave.rb

CarrierWave.configure do |config|
config.fog_credentials = {
    :provider => 'AWS',
    :aws_access_key_id => '----',
    :aws_secret_access_key => '----',
    :region => 'eu-central-1',
}
config.fog_use_ssl_for_aws = false
config.fog_directory = 'bucekt'
config.storage = :fog
end

Upvotes: 1

Views: 4508

Answers (1)

Noman Ur Rehman
Noman Ur Rehman

Reputation: 6957

You must first configure the AWS gem. Add this code to the config/initializers/aws.rb file.

Aws.config.update({
  region: '<default-region>',
  credentials: Aws::Credentials.new('<access-key-id>', '<secret-access-key')
})

You can also set the environment variables AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and AWS_REGION on your server and the SDK will pick them up automatically.

Then, anywhere in your app or a controller action, you can call the S3 API like this:

def some_action
  # You can simply call Aws::S3::Client.new
  # if you are already configuring using the
  # above methods or configure by passing
  # parameters explicitly
  s3_client = Aws::S3::Client.new(
    credentials: Aws::Credentials.new('<aws_access_key_id>', '<aws_secret_key>'),
    region: '<aws_region>'
  )

  # delete object by passing bucket and object key
  s3_response = s3_client.delete_object({
    bucket: '<bucket-name>', # required
    key: '<object-key>', # required
  })
end

Upvotes: 6

Related Questions