2017-03-17 38 views
0

我設置爲locale基本選項application.rb導軌 - 重定向與區域

config.i18n.available_locales = [:pl, :en] 
config.i18n.default_locale = :pl 

而且也作用域路線:

Rails.application.routes.draw do 
    get '/:locale', to: 'home#index' 
    root   to: 'home#index' 

    scope ":locale", locale: /#{I18n.available_locales.join("|")}/ do 
     get 'settings', to: 'home#settings' 
    end 
end 

這樣www.mysite.comwww.mysite.com/en or pl下我可以訪問我的根網站,以及在網址中包含語言環境時的設置網站。

現在讓我們假設用戶輸入www.mysite.com/settings。我希望我的應用知道該網址中沒有語言環境,因此請抓住default_locale,設置它,然後重定向到www.mysite.com/pl/settings

我怎麼能做到這一點?

PS我也開始加入那些我ApplicationController

before_action :set_locale 

    def set_locale 
     I18n.locale = params[:locale] || I18n.default_locale 
    end 

    def default_url_options 
     { locale: I18n.locale } 
    end 

回答

-1
Rails.application.routes.draw do 
    scope ':locale', locale: /#{I18n.available_locales.join("|")}/ do 
    root 'users/landing#index' 
    get '*path', to: 'users/errors#not_found' 
    end 
    root to: redirect("/#{I18n.default_locale}", status: 302), as: :redirected_root 
    get "/*path", to: redirect("/#{I18n.default_locale}/%{path}", status: 302) 
end 
+0

你應該解釋一下你的代碼爲什麼它回答了這個問題。這樣它爲OP提供了更多的幫助。 :) – Markus