ruby-on-rails - Rails - 使用区域设置重定向

标签 ruby-on-rails redirect rails-i18n

我在application.rb中设置了locale的基本选项:

config.i18n.available_locales = [:pl, :en]
config.i18n.default_locale = :pl

并且还确定了路线范围:

Rails.application.routes.draw do
    get '/:locale', to: 'home#index'
    root            to: 'home#index'

    scope ":locale", locale: /#{I18n.available_locales.join("|")}/  do
      get 'settings', to: 'home#settings'
    end
end

这样我就可以访问 www.mysite.comwww.mysite.com/en 或 pl 下的根站点,以及包含时的设置站点网址中的区域设置。

现在假设用户输入了www.mysite.com/settings。我希望我的应用程序知道网址中没有区域设置,因此请获取 default_locale,进行设置,然后重定向到 www.mysite.com/pl/settings.

我怎样才能做到这一点?

PS 我还将它们添加到我的 ApplicationController 中:

before_action :set_locale

    def set_locale
      I18n.locale = params[:locale] || I18n.default_locale
    end

    def default_url_options
      { locale: I18n.locale }
    end

最佳答案

如果用户在接受语言 header 中没有完善,即使您将其他非本地化路由重定向到完善,也最好将根路径重定向到英语。

 # Usefull to parse accept-language header but also for browser detection
 gem 'browser'

在routes.rb中:

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

    # Home
    root 'pages#index'
  end

  root 'pages#detect_locale'

  # Catch all requests without a available locale and redirect to the PL default...
  # The constraint is made to not redirect a 404 of an existing locale on itself
  get '*path', to: redirect("/#{I18n.default_locale}/%{path}"), 
               constraints: { path: %r{(?!(#{I18n.available_locales.join('|')})\/).*} }
end

在 Controller 中:

class PagesController < ApplicationController
  def index; end

  # Detect localization preferences
  def detect_locale
    # You can parse yourself the accept-language header if you don't use the browser gem
    languages = browser.accept_language.map(&:code)

    # Select the first language available, fallback to english
    locale = languages.find { |l| I18n.available_locales.include?(l.to_sym) } || :en

    redirect_to root_path(locale: locale)
  end
end

关于ruby-on-rails - Rails - 使用区域设置重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42863461/

相关文章:

ruby-on-rails - Rails : Edit/Update Record, 使用当前记录字段条目填充文本字段

javascript - 单击链接工作时无法在 div 的两种颜色之间切换

ruby-on-rails - Rails:使用 ActiveRecord::StatementInvalid: PG::NotNullViolation: ERROR 测试失败

ruby-on-rails - i18n-tasks 无法路由键

javascript - Rails - 多个远程表单点击相同的 Controller 操作?

java - 如何重定向到 j_spring_security_check

html - 苹果应用商店角标(Badge)在移动设备上重定向至可疑广告,但在桌面设备上则不然

Python 使用 Javascript 获取重定向 URL

ruby - Rails 4 和全局化不添加翻译

ruby-on-rails - 从国家/地区到语言的语言环境回退,无需单独定义每个语言