点击导航栏链接默认返回到英文



我遵循railscast指南,但由于某种原因,当我单击链接时,参数区域设置没有被传递。

这是我的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}/")

我认为我的应用程序和railcast之间的主要区别是我是在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,因为它不会自动"结转"。为此,只需在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指南

的这一部分。

最新更新