0

I've been implementing an Active Storage Google strategy on Rails 5.2, at the moment I am able to upload files using the rails console without problems, the only thing I am missing is if there is a way to specify a directory inside a bucket. Right now I am uploading as follows

bk.file.attach(io: File.open(bk.source_dir.to_s), filename: "file.tar.gz", content_type: "application/x-tar")

The configuration on my storage.yml

google:
  service: GCS
  project: my-project 
  credentials: <%= Rails.root.join("config/myfile.json") %>
  bucket: bucketname

But in my bucket there are different directories such as bucketname/department1 and such. I been through the documentation and have not found a way to specify further directories and all my uploads end up in bucket name.

del cueto
  • 99
  • 1
  • 6

2 Answers2

2

Sorry, I’m afraid Active Storage doesn’t support that. You’re intended to configure Active Storage with a bucket it can use exclusively.

George Claghorn
  • 24,999
  • 3
  • 40
  • 45
  • 1
    There was a suggested hack in another SO thread around overriding the move_to method that might help: https://stackoverflow.com/questions/48389782/how-to-specify-a-prefix-when-uploading-to-s3-using-activestorages-direct-upload – Brandon Yarbrough May 29 '18 at 22:23
0

Maybe you can try metaprogramming, something like this:

  1. Create config/initializers/active_storage_service.rb to add set_bucket method to ActiveStorage::Service
module Methods
  def set_bucket(bucket_name)
    # update config bucket
    config[:bucket] = bucket_name

    # update current bucket
    @bucket = client.bucket(bucket_name, skip_lookup: true)
  end
end
ActiveStorage::Service.class_eval { include Methods }
  1. Update your bucket before uploading or downloading files
ActiveStorage::Blob.service.set_bucket "my_bucket_name"

bk.file.attach(io: File.open(bk.source_dir.to_s), filename: "file.tar.gz", content_type: "application/x-tar")

bibs
  • 49
  • 3
  • It looks like you've included a link to your own article, or an article you're affiliated with. If this is the case, [you *must* disclose your affiliation in the answer itself](https://stackoverflow.com/help/promotion). – Hoppeduppeanut Nov 24 '20 at 05:49
  • @Hoppeduppeanut thanks, maybe I'll just remove the link – bibs Nov 24 '20 at 06:50
  • No need to remove it, you just need to state that you've written the article, and make sure that it relates to the question being asked and the information you've provided in your answer. – Hoppeduppeanut Nov 25 '20 at 01:30