Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve attachment url with Rails Active Storage with S3

rails version 5.2 

I have a scenario where I need to access the public URL of Rails Active Storage with Amazon S3 storage to make a zip file with Sidekiq background job.

I am having difficulty getting the actual file URL. I have tried rails_blob_url but it gives me following

http://localhost:3000/rails/active_storage/blobs/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaHBBZUk9IiwiZXhwIjpudWxsLCJwdXIiOiJibG9iX2lkIn19--9598613be650942d1ee4382a44dad679a80d2d3b/sample.pdf 

How do I access the real file URL through Sidekiq?

storage.yml

test:   service: Disk   root: <%= Rails.root.join("tmp/storage") %>  local:   service: Disk   root: <%= Rails.root.join("storage") %>  development:   service: S3   access_key_id: 'xxxxx'   secret_access_key: 'xxxxx'   region: 'xxxxx'   bucket: 'xxxxx' 

development.rb

  config.active_storage.service = :development 

I can access fine these on web interface but not within Sidekiq

like image 324
Shani Avatar asked Apr 12 '18 08:04

Shani


People also ask

How do I find the active storage image URL?

Also try @object. image. service_url . This will give you the url where the image is saved.

How do you check S3 URL is valid or not?

You can simply do an HTTP head request to check whether the url exist.

How do I create a URL for Amazon S3?

To generate a presigned URL using the AWS Management ConsoleSign in to the AWS Management Console and open the Amazon S3 console at https://console.aws.amazon.com/s3/ . In the Buckets list, choose the name of the bucket that contains the object that you want a presigned URL for.

What is Active storage in Rails?

Active storage is an inbuilt gem in Rails that developers widely use to handle file uploads. Combined with the encrypted credentials feature in the latest releases of Rails, active storage is a safe and easy method to upload, serve, and analyze files onto cloud-based storage services as well as local storage.


1 Answers

Use ActiveStorage::Blob#service_url. For example, assuming a Post model with a single attached header_image:

@post.header_image.service_url 

Update: Rails 6.1

Since Rails 6.1 ActiveStorage::Blob#service_url is deprecated in favor of ActiveStorage::Blob#url.

So, now

@post.header_image.url 

is the way to go.

Sources:

  • Link to the corresponding PR.
  • Link to source.
like image 78
George Claghorn Avatar answered Sep 20 '22 21:09

George Claghorn