2014-10-20 31 views
0

我有一个多语言轨道使用Rails I18n API使用URL像的Rails的I18n重定向默认语言

“example.com/en/about”或“example.com/de/about”或“例如创建网站。 COM/EN /接触”

这工作得很好原样,但我想,如果一个用户进入‘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,但我更喜欢做这在轨道上。

回答

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