Rails 6 relative_url_root not working for deployment in subdirectory

Viewed 848

I'm deploying a Rails 6 application into a subfolder (/dictionnaire-app). I set config.relative_url_root = "/dictionnaire-app" in application.rb and also added the ENV variable according to the documentation.

However, if assets are properly rendered, links generated with the link_to method are not updated accordingly.

I read many questions related to this problem and tried to create a scope in my routes.rb file, following these instructions.

Rails.application.routes.draw do
    mount ForestLiana::Engine => '/forest'
    root to: "home#index"

    scope 'dictionnaire-app' do
        resources :words, path: "definition", param: :slug

        post '/search', to: 'words#search'
        get '/recherche', to: 'words#search_page'
        get '/:letter', to: 'words#alphabet_page', param: :letter, as: "alphabetic_page"
    end
    
end

Unfortunately the app throws an error saying the page doesn't exist for this URL : https://www.lalanguefrancaise.com/dictionnaire-app/definition/rameal

However, this URL works: https://www.lalanguefrancaise.com/dictionnaire-app/dictionnaire-app/definition/rameal

Any idea of how can I solve this issue and render the app on /dictionnaire-app/*?

Thanks.

Edit: this issue seems to be from Rails (see here). Any way to find a work around?

1 Answers

I haven't tried this before, but I would imagine something like this might work:

# config/routes.rb
if Rails.application.config.relative_url_root == "/dictionnaire-app"
  extend DictionaryRoutes
else
  scope 'dictionnaire-app' do
    extend DictionaryRoutes
  end
# config/routes/dictionary_routes.rb
module DictionaryRoutes
  def self.extended(router)
    router.instance_exec do
      resources :words, path: "definition", param: :slug

      post '/search', to: 'words#search'
      get '/recherche', to: 'words#search_page'
      get '/:letter', to: 'words#alphabet_page', param: :letter, as: "alphabetic_page"
    end
  end
end

Typically you wouldn't want to use if-else in routes, but in this case, you are in fact defining whether a route exists or not for the app dynamically. Might need more customization to get this working right. Assuming you are trying to allow /search as your route not /dictionnaire-app/search (or that is causing the issue).

Though seeing that hasn't been posted, it's unclear if that's going to be that simple of a fix.

Related