Search code examples
ruby-on-railsrails-activestorage

Rails Active Storage: Direct upload from model


I am creating a sitemap for my website and I need to upload it to S3, because of Heroku temporary filesystem.

I have already configured Active Storage with Amazon S3 but I don't want to create a Model entity only for a single upload. Is there a way just to:

sitemap.rb

  1. Upload the file generated "public/sitemaps/sitemap.xml.gz" to S3 with Active Storage
  2. Retrieve the URL

Solution

  • Wrong tool.

    Active Storage facilitates uploading files to a cloud storage service like Amazon S3, Google Cloud Storage, or Microsoft Azure Storage and attaching those files to Active Record objects.

    ActiveStorage is built around attaching files to models. Trying to use it without a model will be very painful as you are working against the entire design of ActiveStorage.

    If you just want to upload a file created on the server then use the aws-sdk-ruby gem instead.

    require 'aws-sdk-s3'
    
    s3 = Aws::S3::Resource.new(region:'us-west-2')
    obj = s3.bucket('bucket-name').object('key')
    obj.upload_file('/path/to/source/file', { acl: 'public-read' })
    # Returns Public URL to the file
    obj.public_url
    

    See upload an Object Using the AWS SDK for Ruby.