0

我想從瀏覽器中得到非符號的語言的用戶爲了這個,我有這樣的代碼在我的應用程序控制器允許現場切換的Rails的I18n HTTP_ACCEPT_LANGUAGE

def set_locale 
    if user_signed_in? && !current_user.language.blank? 
     I18n.locale = current_user.language 
    else 
     I18n.locale = extract_locale_from_accept_language_header 

     if user_signed_in? && current_user.language.blank? 
     current_user.language = I18n.locale 
     current_user.save 
     end 
    end 
    end 

    def default_url_options(options={}) 
    { :locale => I18n.locale } 
    end 

    private 

    def extract_locale_from_accept_language_header 
    preferred_language = request.env['HTTP_ACCEPT_LANGUAGE'] || '' 
    preferred_language = preferred_language.scan(/^[a-z]{2}/).first 
    available_locales= ("en" "fr") 
    if available_locales.include?(preferred_language) 
     preferred_language 
    else 
     "en" 
    end 
    end 

想我的瀏覽器語言是法語,這給我http://localhost:3000/fr但問題是,當用戶改變語言的非標誌英語,去例如http://localhost:3000/en/users/sign_up另一個頁面的語言會改變法國,所以我得到http://localhost:3000/fr/users/sign_up而不是http://localhost:3000/en/users/sign_up所以我不知道我怎樣才能解決這個問題

這是我的路線文件

更新

scope :path => ":locale" do 
....... 
end 

# Catch all requests without a locale and redirect to the default... 
    get '*path', to: redirect("/#{I18n.default_locale}/%{path}"), constraints: lambda { |req| !req.path.starts_with? "/#{I18n.default_locale}/" } 
    get '', to: redirect("/#{I18n.default_locale}") 
+48

請不要污衊你的帖子。 Stack Overflow的內容旨在幫助* everyone,而不僅僅是你。 – BradleyDotNET

+1

此外,如果您希望與內容無關(無論出於何種原因),您可以使用「自定義」/「其他」標誌(不能取消關聯內容,但可以* *聯繫開發人員/ SE員工讓他們這樣做),或者您可以[直接聯繫團隊](http://stackoverflow.com/contact),讓他們代表您這樣做。 –

回答

2

我認爲這將解決您的問題:

def set_locale 
    if user_signed_in? && !current_user.language.blank? 
     I18n.locale = current_user.language 
    else 
     I18n.locale = if params[:locale].present? 
         params[:locale] # Here you might want to do some checking to allow only your desired locales 
        else 
         extract_locale_from_accept_language_header 
        end 

     if user_signed_in? && current_user.language.blank? 
     current_user.language = I18n.locale 
     current_user.save 
     end 
    end 
    end 

這將給優先於URL指定的區域設置(en | fr)通過HTTP_ACCEPT_LANGUAGE頭。

+0

但是,當嘗試訪問http:// localhost:3000 /時,即使我的瀏覽器語言是法語 – userails

+0

,但它總是會給我http:// localhost:3000/en它不應該。如果你訪問localhost:3000,那麼'params [:locale]'不會出現,然後它會運行extract_locale方法給你法語,如果你的瀏覽器被設置爲使用這種語言。 – sjaime

+0

如果你被重定向到'/ en',那麼在其他地方設置'locale'參數,例如'routes.rb'文件。 – sjaime