今天是个好日子,
我正在使用Rails 4,在我的网站中,我正在使用以下链接来处理语言环境:
en - http://www.sample.com/XXXXX
zh-HK - http://www.sample.com/zh-HK/XXXXX
zh-CN - http://www.sample.com/zh-CN/XXXXX
此外,我正在使用自定义错误页面方法来处理404、422和500错误。
即
config/routes.rb
scope "(:locale)", :locale => /en|zh-CN|zh-HK/ do
root 'home#index'
get '/' => 'home#index', as: :home_page
get 'about' => 'home#about', as: :about_page
end
%w( 404 422 500 ).each do |code|
get code, :to => "errors#show", :code => code
end
get '/:locale' => 'home#index'
config/environment/production.rb
Rails.application.configure do
config.exceptions_app = self.routes
end
app/controller/application_controller.rb
class ApplicationController < ActionController::Base
before_filter :set_locale
def set_locale
I18n.locale = params[:locale] || I18n.default_locale
end
end
app/controller/errors_controller.rb
class ErrorsController < ApplicationController
def show
render status_code.to_s, :status => status_code, :layout => false
end
protected
def status_code
params[:code] || 500
end
end
****************这是我的问题。******************
当我在http://www.sample.com/zh-HK/abc这样的模式中输入错误的链接时,
它可以显示自定义错误页面。
但是当我输入错误的链接时http://www.sample.com/abc
(没有语言环境(实际上应该是默认语言环境:en)),
这不会转到我的自定义错误页面。
相反,它给了我这样的错误页面:
如何解决此问题,以便在使用默认语言环境(即链接中没有语言环境)时可以使用自定义错误页面?谢谢!
最佳答案
尝试将所有不匹配的路由重定向到默认语言环境,如下所示:
scope "(:locale)", :locale => /en|zh-CN|zh-HK/ do
root 'home#index'
get '/' => 'home#index', as: :home_page
get 'about' => 'home#about', as: :about_page
end
%w( 404 422 500 ).each do |code|
get code, :to => "errors#show", :code => code
end
root to: redirect("/en", status: 302), as: :redirected_root
get "/*path",
to: redirect("/en/%{path}", status: 302),
constraints: {path: /(?!(en|zh-CN|zh-HK)})\/).*/},
format: false
关于ruby-on-rails - Rails 4处理语言环境错误页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36870489/