0

我遵循railscast指南,但由於某種原因,當我單擊某個鏈接時,params語言環境未被結轉。I18n單擊導航欄鏈接默認返回英文

這裏是我的routes.db

Rails.application.routes.draw do 
scope ":locale", locale: /#{I18n.available_locales.join("|")}/ do 

get 'welcome/index' 

# The priority is based upon order of creation: first created -> highest priority. 
# See how all your routes lay out with "rake routes". 

# You can have the root of your site routed with "root" 
root 'welcome#index' 

resources :foods 
resources :shops 
resources :communities 
resources :events 
resources :pictures 
resources :videos 
resources :services 

end 
get '*path', to: redirect("/#{I18n.default_locale}/%{path}") 
get '', to: redirect("/#{I18n.default_locale}/") 

我想我的應用程序和railscasts之間的主要區別是我做它的application.html.erb模板。所以我想知道這是否會影響它。

謝謝你的時間!

編輯:

應用控制器

class ApplicationController < ActionController::Base 
    # Prevent CSRF attacks by raising an exception. 
    # For APIs, you may want to use :null_session instead. 
    protect_from_forgery with: :exception 
    before_action :set_locale 

private 
    def set_locale 
     I18n.locale = params[:locale] if params[:locale].present? 
end 

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

編輯:

<li><a href="/foods"><i class="fa fa-cutlery" aria-hidden="true"></i> <%= t('layouts.application.food') %><span class="sr-only">(current)</span></a></li> 
+1

的這一部分您能否顯示「不包含區域設置」的確切'link_tag'?我的猜測是你沒有把它傳遞給你的url helper方法,e..g'blah_path'而不是'blah_path(locale :: es)'。 –

+0

@JanBussieck我添加了鏈接標籤。謝謝。 –

+1

好的,看看下面的答案。使用url和路由助手,比如'link_to「Foods」,foods_path',在你的情況下你沒有傳入地址爲url參數。 –

回答

1

locale範圍在你的路由文件只是確保你的位置設置根據URL字符串中的標識符。但是,您仍然必須在應用程序中生成包含此標識符的URL,因爲它不會自動「結轉」。要做到這一點,只需在application_controller.rb像這樣設置默認網址選項:

def default_url_options(options = {}) 
    if I18n.default_locale != I18n.locale 
    {locale: I18n.locale}.merge options 
    else 
    {locale: nil}.merge options 
    end 
end 

現在每次你調用一個路線助手等具有books_path當前區域將作爲URL參數傳遞,就像它將如果你做如此明確地; book_path(locale: I18n.locale)

由於默認區域設置爲default_url_options,因此這也允許您擺脫routes.rb底部的球狀路線。 您還應該查看rails guides