Search code examples
ruby-on-railsrails-activestorage

ActiveStorage direct upload is having a wrong Request URL in Staging but not in dev: https://xxxxxx/rails/active_storage/direct_uploads


I am facing a strange issue with Activestorage on Rails 5.2 and using DigitalOcean spaces (s3 compatible storage), the problem is that the uploading works well in the development environment but it does not work in staging environment

After searching a lot on why that happens, I noticed the following:

In development environment, the url for the direct upload is like this: Request URL: http://localhost:3000/rails/active_storage/direct_uploads

In staging environment, the url for the direct upload is like this: Request URL: http://localhost/rails/active_storage/direct_uploads and if I change this input to have the staging environment hostname manually, the upload works fine

Request URL: http://stagingHostName/rails/active_storage/direct_uploads

Therefore, how to adjust the host name for upload in Activestorage in the configuration?


Solution

  • I finally found the answer for this & I hope this helps someone else, that direct-url is built based on the following option:

    So inside application_controller.rb, you might need to add or adjust the following method & make sure environment variable HOST is defined in your environment, so that the url will be built correctly:

      def default_url_options(_options = {})
        host = Rails.env.production? || Rails.env.staging? ? ENV["HOST"] : "localhost:3000"
        { host: host, locale: (some logic to handle the locale)}
      end