Rails 中的路线冲突
Routes conflict in Rails
我需要接下来的 3 条路线:
get "", to: redirect("/#{I18n.locale}")
get '/:locale/', to: "home#index"
get "/*path", to: redirect("/#{I18n.default_locale}/%{path}", status: 302), constraints: {path: /(?!(#{I18n.available_locales.join("|")})\/).*/}, format: false
在这种情况下,当我转到 domain.com
时,它会将我重定向到 domain.com/en
。没关系。但是当我输入 domain.com/feed
时,它会出现错误。我该如何解决这个错误?
我可以这样写吗
if params[:locale] == "en"
get "", to: redirect("/#{I18n.locale}")
get '/:locale/', to: "home#index"
else
get "/*path", to: redirect("/#{I18n.default_locale}/%{path}", status: 302), constraints: {path: /(?!(#{I18n.available_locales.join("|")})\/).*/}, format: false
end
还是别的?
一个错误:
"feed" is not a valid locale
def set_locale
I18n.locale = params[:locale] || I18n.default_locale
end
您必须先 "constrain" 语言环境路由,否则它将捕获所有。所以做一些像
get '/:locale/', to: "home#index", constraints: {locale: /en|de/}
参见 documentation 你可以给一个正则表达式来限制路由,在这种情况下:只允许 en
和 de
语言环境。
如果您的区域设置列表很长并且将来可能会更改,这会变得乏味,因此您也可以这样写:
get '/:locale/', to: "home#index", constraints: {locale: /#{I18n.available_locales.join("|")}/ }
我需要接下来的 3 条路线:
get "", to: redirect("/#{I18n.locale}")
get '/:locale/', to: "home#index"
get "/*path", to: redirect("/#{I18n.default_locale}/%{path}", status: 302), constraints: {path: /(?!(#{I18n.available_locales.join("|")})\/).*/}, format: false
在这种情况下,当我转到 domain.com
时,它会将我重定向到 domain.com/en
。没关系。但是当我输入 domain.com/feed
时,它会出现错误。我该如何解决这个错误?
我可以这样写吗
if params[:locale] == "en"
get "", to: redirect("/#{I18n.locale}")
get '/:locale/', to: "home#index"
else
get "/*path", to: redirect("/#{I18n.default_locale}/%{path}", status: 302), constraints: {path: /(?!(#{I18n.available_locales.join("|")})\/).*/}, format: false
end
还是别的?
一个错误:
"feed" is not a valid locale
def set_locale
I18n.locale = params[:locale] || I18n.default_locale
end
您必须先 "constrain" 语言环境路由,否则它将捕获所有。所以做一些像
get '/:locale/', to: "home#index", constraints: {locale: /en|de/}
参见 documentation 你可以给一个正则表达式来限制路由,在这种情况下:只允许 en
和 de
语言环境。
如果您的区域设置列表很长并且将来可能会更改,这会变得乏味,因此您也可以这样写:
get '/:locale/', to: "home#index", constraints: {locale: /#{I18n.available_locales.join("|")}/ }