Search code examples
ruby-on-railsmethodsinternationalizationlocale

Reveiving a "undefined method `locale' for nil:NilClass" error when using I18n in Rails


I am trying to set the local of my users via a field in my user model called locale. However, the I18n methods do not seem to be working. I'm not sure if I've missed some configuration or something. (I'm still new to rails.) I find that this also happens with many gems that I try to use. Possible that I am initializing things incorrectly?

undefined method default_locale for nil:NilClass

In my Application Controller:

 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

Solution

  • I am pretty sure that your current_user is nil. Just make sure that the current_user is set before you call locale on it.