【问题标题】:Reveiving a "undefined method `locale' for nil:NilClass" error when using I18n in Rails在 Rails 中使用 I18n 时出现“nil:NilClass 的未定义方法 `locale'”错误
【发布时间】:2014-02-14 14:55:26
【问题描述】:

我正在尝试通过我的用户模型中名为 locale 的字段来设置我的用户的本地。 但是,I18n 方法似乎不起作用。我不确定我是否错过了一些配置或其他东西。 (我对 Rails 还是很陌生。)我发现这也发生在我尝试使用的许多 gem 上。可能是我初始化不正确?

undefined method default_locale for nil:NilClass

在我的应用程序控制器中:

 before_filter :set_locale 

 private 

 def set_locale # Sets the users language via the locale index. 
    I18n.default_local = 'en'
    I18n.locale = current_user.locale if current_user.locale.present? || I18n.default_locale
 end

【问题讨论】:

  • set_locale 方法中我看到I18n.default_local = 'en'。你的意思是I18n.default_locale = 'en'
  • 你的权利,我错过了输入它。我有另一个错误,但这可能是问题所在。 (我的视力很差,-8.3!)
  • 您应该在I18n.default_local = 'en' 首先声明undefined method default_local=' for I18n:Module 时遇到错误。
  • 您的current_user 似乎为零。检查其值是否已设置。
  • 好的,你说得对。我认为由于我在应用程序控制器上使用了前置过滤器,因此我的方法在用户登录之前就被访问了。(通过设计)

标签: ruby-on-rails methods internationalization locale


【解决方案1】:

我很确定你的current_user 是零。只需确保在调用 locale 之前设置了 current_user

【讨论】:

  • def set_locale # 通过区域索引设置用户语言。 I18n.default_locale = 'en' # 设置默认为英文。如果 current_user.nil? # 用户未登录。 else I18n.locale = current_user.locale if current_user.locale.present? || I18n.default_locale end end
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多