我正在开发一个多语言 Rails 应用程序,我需要每个区域的路线都不同。这样对我来说很难解释,所以我举个例子:
- en:/en/定价
- es:/es/precios
我找到了这个答案:Rails 4 i18n, how to translate routes where subdomain is used for the locale
因此我的routes.rb看起来像这样:
scope "/:locale" do
get "/", to: "pages#index", as: "index"
get "/#{I18n.t("pricing")}", :to => "pages#pricing", :as => "pricing"
end
我还在应用程序加载(应用程序 Controller before_action)上使用 AppName::Application.reload_routes!
,但就在区域设置更改之后,/locale 后的 URI 其余部分保持不变 - 即当用户尝试重新加载页面时会出现问题,因为该页面不再存在。使用新的区域设置 URI,其他点击都可以。
我正在考虑一种系统来查明我当前的 URI 是否正确,如果不正确,则将其重定向到那里,但我认为这不是最理想的。您有什么建议吗?
提前谢谢您。
最佳答案
我一直在使用rails-translate-routes gem 出于此目的已经在生产站点中使用一段时间了( Qoolife is an example you can check )。
如果您使用 I18n 作为翻译后端,它会表现得很好。如果你的项目恰好使用gettext另外,看看my fork of the gem 。作为替代方案,您可以查看 route_translator gem 。
对于其中任何一个,代码看起来都非常相似:
# 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
然后,您需要使用路由约束或在 ApplicationController
中从子域设置您的区域设置
。看看this issue讨论这一点的地方。
关于ruby-on-rails - 基于区域设置的 Rails 路线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27319935/