我正在关注railscast指南,但出于某种原因,当我点击链接时,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}/")
我认为我的应用程序和railscast之间的主要区别在于我在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>
答案 0 :(得分: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)
。
这也允许你摆脱routes.rb
底部的全局路由,因为默认语言环境默认设置在default_url_options
中。
您还应该参考rails guides