Rails I18n重定向默认语言

时间:2014-10-20 20:44:26

标签: ruby-on-rails routes url-redirection rails-i18n

我有一个使用Rails I18n API创建的多语言rails网站,其网址为

“example.com/en/about”或“example.com/de/about”或“example.com/en/contact”

这样可以正常工作,但我希望如果用户转到“example.com/about”(没有URL中的语言部分),他将被重定向到默认语言的相应页面,例如到“example.com/en/about”

我的config / routes.rb看起来像:

Example::Application.routes.draw do
  get '/:locale' => 'static_pages#home'
  scope "/:locale" do
    root "static_pages#home"
    match 'about', to: 'static_pages#about', via: 'get'
    match 'contact', to: 'contact#new', via: 'get'
  end
  resources "contact", only: [:new, :create]
end

我可以在服务器(apache)级别重定向URL,但我更喜欢在rails中执行此操作。

1 个答案:

答案 0 :(得分:0)

你可以做那样的事 在你的路线

Rails.application.routes.draw do
  scope "(:locale)", locale: /en|es/ do


  root                'static_pages#home'
  get 'static_pages' => 'static_pages#home'
  get '/:locale' => 'static_pages#home'
  get    'help'    => 'static_pages#help'
  get    'about'   => 'static_pages#about'
  get    'contact' => 'static_pages#contact'
  get    'signup'  => 'users#new'
  get    'login'   => 'sessions#new'
  post   'login'   => 'sessions#create'
  delete 'logout'  => 'sessions#destroy'
  end

在你的ApplicationController中

    before_action :set_locale

  def set_locale
    if params[:locale] && I18n.available_locales.include?(params[:locale].to_sym)
      cookies['locale'] = { :value => params[:locale], :expires => 1.year.from_now }
      I18n.locale = params[:locale].to_sym
    elsif cookies['locale'] && I18n.available_locales.include?(cookies['locale'].to_sym)
      I18n.locale = cookies['locale'].to_sym
    end
  end

  protect_from_forgery

    def default_url_options(options={})
    logger.debug "default_url_options is passed options: #{options.inspect}\n"
    { :locale => I18n.locale }
     end

  def extract_locale_from_tld
    parsed_locale = request.host.split('.').last
    I18n.available_locales.map(&:to_s).include?(parsed_locale) ? parsed_locale : nil
  end