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.