Peter DeWeese
Peter DeWeese

Reputation: 18333

How can I customize the path of a Rails 5.2 ActiveStorage attachment in Amazon S3?

When adding attachments such as

has_one_attached :resume_attachment

saved files end up in the top level of the S3 bucket. How can I add them to subdirectories? For example, my old paperclip configuration could categorize in directories by model name.

Upvotes: 19

Views: 5782

Answers (2)

dtbaker
dtbaker

Reputation: 4919

Use a before_validation hook to set the desired key on S3 and the desired filename for the content disposition object properties on S3.

The key and filename properties on the attachment model make their way through to the ActiveStorage S3 gem and are converted into S3 key + content disposition object properties.


class MyCoolItem < ApplicationRecord
  has_one_attached :preview_image
  has_one_attached :download_asset

  before_validation :set_correct_attachment_filenames

  def preview_image_path
    # This key has to be unique across all assets. Fingerprint it yourself.
    "/previews/#{item_id}/your/unique/path/on/s3.jpg"
  end

  def download_asset_path
    # This key has to be unique across all assets. Fingerprint it yourself.
    "/downloads/#{item_id}/your/unique/path/on/s3.jpg"
  end
  
  def download_asset_filename
    "my-friendly-filename-#{item_id}.jpg"
  end

  def set_correct_attachment_filenames
    # Set the location on S3 for new uploads:
    preview_image.key = preview_image_path if preview_image.new_record?
    download_asset.key = download_asset_path if download_asset.new_record?

    # Set the content disposition header of the object on S3:
    download_asset.filename = download_asset_filename if download_asset.new_record?
  end
end

Upvotes: 1

Dinatih
Dinatih

Reputation: 2476

You can not. There is only one option possible, at that time, for has_one_attached, has_many_attached macros that is :dependent. https://github.com/rails/rails/blob/master/activestorage/lib/active_storage/attached/macros.rb#L30

see (maybe the reason why you have downvotes, but it is about "direct" upload so...) : How to specify a prefix when uploading to S3 using activestorage's direct upload?. The response is from the main maintainer of Active Storage.

Upvotes: 5

Related Questions