Search code examples
ruby-on-railsruby-on-rails-4routesrails-i18n

Rails routes based on locale


I'm working on a multilingual rails app and I need the routes to be different for each locale. It's difficult to explain it like this for me, so I'll use an example:

  • en: /en/pricing
  • es: /es/precios

I found this answer: Rails 4 i18n, how to translate routes where subdomain is used for the locale

Therefore my routes.rb looks like this:

scope "/:locale" do            
  get "/", to: "pages#index", as: "index"
  get "/#{I18n.t("pricing")}", :to => "pages#pricing", :as => "pricing"
end

I'm also using AppName::Application.reload_routes! on app loading (application controller before_action), but just right after a locale change the rest of URI after /locale stays the same - that makes a problem when user tries to reload the page because that is non-existent any more. Other clicks are okay, with new locale URIs.

I'm thinking of a system to find out whether my current URI is the correct one and if not, redirect it there, but I think this is suboptimal. Do you have any suggestions?

Thank you in advance.


Solution

  • I have monkey-patched a solution for this problem. Just set a before_action confirm_path in the application controller just after setting the locale.

    def confirm_path 
      current_path = Rails.application.routes.recognize_path(request.env['PATH_INFO'])
      MyApp::Application.reload_routes!
      correct_url = url_for(controller: current_path[:controller], action: current_path[:action])  
      if correct_url != request.original_url
        redirect_to correct_url, status: 301
      end
    end
    

    I do not really recommend this answer and I know it is not ideal. Use a gem instead as @dgilperez have mentioned. I'm posting it just in case someone's in a situation when it's too late to refactor your code.