Reputation: 90
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:
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.
Upvotes: 2
Views: 1706
Reputation: 90
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.
Upvotes: -1
Reputation: 10796
I've been using rails-translate-routes gem for this exact purpose for a while now in production sites (Qoolife is an example you can check).
If you are using I18n as the translation backend, it will behave just fine. If your project happens to use gettext as well, have a look at my fork of the gem. As an alternative, you can have a look at route_translator gem.
With any of those, the code would look quite similar:
# config/routes.rb
ActionDispatch::Routing::Translator.translate_from_file('config/locales/routes.yml')
# config/locales/routes.yml
en:
routes:
# you can leave empty locales, for example the default one
es:
routes:
pricing: precios
Then you will need to set your locale
from the subdomain using a route constraint or in your ApplicationController
. Have a look at this issue where this particular is discussed.
Upvotes: 3