Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveStorage::Current.host= is deprecated, how can i use ActiveStorage::Current.url_options

I render urls for my active record attachments in erb files with url method.

#controller    
class RecordMetadataController < ApplicationController
        before_action do
        ActiveStorage::Current.host = request.base_url
      end
    .
    .
    .
    end


#view
    <iframe src="<%= file.url expires_in: 30 ,disposition: :inline %>" width="600" height="750" style="border: none;"></iframe>

Rails gives DEPRECATION WARNING in my console so i tried to update my code but i cant make it work.

***DEPRECATION WARNING: ActiveStorage::Current.host= is deprecated, instead use ActiveStorage::Current.url_options***

updatded code

#controller
...
ActiveStorage::Current.url_options = request.base_url
...

new error

in web console i am trying to get full url for file

>> file.url
ArgumentError: Cannot generate URL for K01_D01_G12.pdf using Disk service, please set ActiveStorage::Current.url_options.

can anybody help?

like image 475
Sercan Tırnavalı Avatar asked Dec 22 '25 00:12

Sercan Tırnavalı


2 Answers

ActiveStorage::Current.url_options is actually a Hash that has separate keys for protocol, host, and port. Thus you would need:

before_action do
  ActiveStorage::Current.url_options = { protocol: request.protocol, host: request.host, port: request.port }
end

Alternatively, ActiveStorage provides a concern (ActiveStorage::SetCurrent) that does just that. So, you should be able to do the following:

class RecordMetadataController < ApplicationController
  include ActiveStorage::SetCurrent
  ...
end
like image 82
rmlockerd Avatar answered Dec 24 '25 13:12

rmlockerd


Note: If you are seeing this in rspec then follow this

You can put this spec/rails_helper.rb file

RSpec.configure do |config|
  # Fixes Error after Rails 7.0 upgrade
  #   "Cannot generate URL for 50by50.gif using Disk service, please set ActiveStorage::Current.url_options".
  ActiveStorage::Current.url_options = {host: "https://www.example.com"}
like image 43
illusionist Avatar answered Dec 24 '25 13:12

illusionist



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!