Upload with S3, how to see the VersionId of my object key?

Hi!

Thanks for your awesome work on this gem!

Is somebody knowns how to catch the VersionId of a S3 object after uploading the file?

I use Shrinerb on a rails application.

In a ActiveRecord model i attach a file which is versioned on my S3 bucket.

Each time i upload the file, i search if the file is already present on the bucket and use the same key to be sure i overwrite it.

Finally i would like to add the S3 object version_id of the file in my file metadata.

Doing this, will allow me to generate a link of the file for each version present on the S3 bucket.

Do you know how to do that?

Yes that is easily done using the AWS ruby sdk:

bucket.versioning_enabled? # => true
version = bucket.objects["mykey"].versions.latest

Now you can get the current “version” of your file and update it according to your needs.

You can also use Shrine to get what you want:

https://github.com/shrinerb/shrine/blob/c63a7af60a7b26daca8be312a94566393b78aad7/lib/shrine/storage/s3.rb#L214 and use the object(id)

Here is an example (untested):
# there are probably more efficient ways of doing this

class Photo < ActiveRecord::Base
  include ImageUploader::Attachment(:image) # adds an `image` virtual attribute 
end

id = photo.image.id # this gets the UploadedFile object.
latest_version = photo.image.storage.object(id).versions.latest

You may want to double check the above in case i’ve made an error somewhere.

Hope this helps!

1 Like

Hi @BKSpurgeon!

Yes, it helps! Thanks!
I was using the AWS-SDK:

        s3_options = {
          bucket: ENV['AWS_UPLOADS_BUCKET'],
          access_key_id: Rails.application.credentials.config[:aws][:uploads][:access_key_id],
          secret_access_key: Rails.application.credentials.config[:aws][:uploads][:secret_access_key],
          region: ENV['AWS_UPLOADS_REGION'],
        }

        s3 = Shrine::Storage::S3.new(**s3_options)
        s3.object(commit.file.id).version_id

It’s better with your example :

commit.file.storage.object(commit.file.id)&.version_id