Search code examples
ruby-on-railsrails-routingrails-activestorage

Rails ActiveStorage rails_blob_path generating invalid url with missing /rails in start


I am on: Rails: 6.0.1
Ruby: 2.6.5

And I am using Rails.application.routes.url_helpers.rails_blob_path helper in one of my serializers to generate path to a pdf file. And it has been working great in development. Generating url like: /rails/active_storage/blobs/:signed_id/*filename
as expected.

But in production, same helper produces wrong url in the format of:
/active_storage/blobs/:signed_id/*filename
notice the missing /rails part in start.

This obviously causes no route matches errors when the url is accessed.

I have been trying to dig and find cuase, temporarily i have added following to my routes.rb

get '/active_storage/blobs/:signed_id/*filename', to: 'active_storage/blobs#show'

I know this is just a hack, but it works for now. I am looking for the real reason and fix through this question.


Solution

  • So i was doing some hit and trial and I noticed this was happening in my production console:

    Rails.application.routes.url_helpers.url_for(Record.last.file)
    => "https://mywebsite.com//rails/active_storage/blobs/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaHBDQT09IiwiZXhwIjpudWxsLCJwdXIiOiJibG9iX2lkIn19--8994a079b16e683a18ef1be83a6ae7f5c3/filename.pdf"
    

    Notice the //rails part, it is invalid as it has double forward slashes. This lead me to the solution.

    Solution

    I had this in my config/environment.rb file:

    Rails.application.default_url_options = Rails.application.config.action_mailer.default_url_options
    

    and default url options in production.rb looked like:

    config.action_mailer.default_url_options = { host: ENV['SERVER_URL'] }
    

    SERVER_BASE_URL was the culprit, it was set to: https://mywebsite.com/ when i changed this to https://mywebsite.com and restarted my server. Boom!

    Although it is not very clear to me WHY is this behavior as such and if this is a bug. But this is what worked for me after hours of struggle.