6

I have a document model which uses ActiveStorage to add attachments to documents:

class Document < ApplicationRecord
 has_one_attached :attachment
end

I also have an existing S3 bucket with images in various formats: jpg, png.

I need to create a new document, where the attachment is a specific image already in my S3 bucket.

So far, I have tried:

s3 = Aws::S3::Resource.new(region: "us-east-1")
obj = s3.bucket("my-bucket-name").object("s3-object-key")
params = {
 filename: obj.key, 
 content_type: obj.content_type, 
 byte_size: obj.size, 
 checksum: obj.etag.gsub('"',"")
}
blob = ActiveStorage::Blob.create_before_direct_upload!(params)

This successfully creates the ActiveStorage::Blob object

But then when I try to create a document, like this:

d = Document.create!(attachment:blob.signed_id, name: "new document")

It seems to be linking the attachment but I cannot view or download the attachment, and normal active storage methods like the following are no longer working:

<%= link_to "View", document.attachment.service_url if doc.attachment %>

I just get this error:

undefined method `service_url' for #<ActiveStorage::Attached::One:0x00007fd7d3f161e0>

If anyone has a better suggestion for how to create a document with an attachment that corresponds to an existing file in S3, that would be much appreciated.

rhosyn
  • 116
  • 8
  • How did you manage to get your files analysed? I've used a very similar method here to create the blob but I keep getting an ActiveStorage::IntegrityError Did setting the checksum field to be equal to the S3 eTag really work for you? I can't figure it out. It's very annoying! – rctneil Oct 30 '22 at 17:59

1 Answers1

0

It appears you've successfully created the attachment, however there's an issue with your download link. (For anyone else with similar questions regarding the attachment, here's another discussion/example: Rails ActiveStorage attachment to existing S3 file).

In order to create your download link, you should instead be using rails_blob_path:

<%= link_to "View", rails_blob_path(document.attachment, disposition: "attachment") %>

You can learn more about this in the Rails docs here: https://edgeguides.rubyonrails.org/active_storage_overview.html#serving-files

edieemm
  • 1
  • 1