I18n 点击导航栏 link 默认返回英文

I18n clicking navbar link defaults back to English

我正在按照 railscast 指南进行操作,但出于某种原因,当我单击 link 时,params 区域设置未被保留。

这是我的 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>

路由文件中的 locale 范围只是确保根据 url 字符串中的标识符设置区域设置。但是,您仍然必须在应用程序中生成包含此标识符的 url,因为它不会自动 'carried over'。为此,只需在 application_controller.rb 中设置默认的 url 选项,如下所示:

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).

这还允许您摆脱 routes.rb 底部的 globbed 路由,因为默认区域设置默认设置在 default_url_options 中。 您还应该查阅 rails guides

的这一部分