【问题标题】:RubyOnRails - Does not keep the selected language when I refresh the pageRubyOnRails - 刷新页面时不保留所选语言
【发布时间】:2015-07-04 17:26:14
【问题描述】:

在开发模式下一切正常。但不是在 heroku 上的生产模式。

当我选择区域设置并刷新页面时,默认情况下显示语言的一半时间,否则显示我选择的语言。我不知道该怎么办。我尝试使用 Rails.cache.clear 命令清除缓存,但它不起作用。我想问题出在缓存系统上。我是 ruby​​ on rails 的新手。有人会知道如何解决这个问题?

要了解我的问题,您可以访问我的网站,选择法语并刷新页面几次。一旦页面是法语。再来一次英语。

https://releaseit.herokuapp.com/

我的应用程序控制器:

  before_action :set_locale
  def set_locale
    if params[:locale].in? %W(en fr)
      I18n.locale = params[:locale]
    end
  end

配置文件与此处相同:https://github.com/starterkits/rails4-starterkit/tree/master/config

对不起我的英语(我是法国人,我使用谷歌翻译)

【问题讨论】:

  • 您是如何配置语言首选项的?你能添加一些代码吗?现在无法判断出了什么问题。
  • 是的,我已经编辑了我的问题

标签: ruby-on-rails caching heroku rails-i18n


【解决方案1】:

我不知道(或看不到)您在 URL 中的何处传递语言环境。据我所知,为了使用params[:locale],您的 URL 应如下所示:

https://releaseit.herokuapp.com/fr/something
https://releaseit.herokuapp.com/en/something
https://releaseit.herokuapp.com/en
https://releaseit.herokuapp.com?locale=fr

http://guides.rubyonrails.org/i18n.html#setting-the-locale-from-the-url-params

还有什么可以试试我的set_locale 方法:

  def set_locale    
    if params[:locale]
      I18n.locale = params[:locale] || I18n.default_locale
    else
      I18n.locale = http_accept_language.compatible_language_from(
        I18n.available_locales
      )
    end
  end

set_locale 方法应在每次页面重新加载时执行,以每次设置正确的语言环境。

它需要来自https://github.com/iain/http_accept_languagehttp_accept_language gem

还可以查看 route_translator gem 以使用语言环境创建路线。

【讨论】:

  • 我找了很久才解决我的问题。我确信我应该调用我的 set_locale 函数一次,因为该站点仍然使用所选语言。非常感谢。
  • 好吧,我没有提到这一点,但我很高兴您根据我的回答弄清楚了。我会更新的。
猜你喜欢
  • 2019-10-24
  • 2014-07-24
  • 1970-01-01
  • 1970-01-01
  • 2020-06-28
  • 2021-03-07
  • 1970-01-01
  • 2011-08-23
  • 1970-01-01
相关资源
最近更新 更多