Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord errors, how do I find out the locale path to change the messages?

I know you can change ActiveRecord error messages in the locales like this:

en:
  activerecord:
    errors:
      models:
        user:
          attributes:
            email:
              blank: "is required"

But that is an incredibly specific tree—how do I know what ActiveRecord is looking for? Is there a way to inspect an error to see what path ActiveRecord is searching? Or is there a way to generate a complete en.yml with all messages in there?

like image 958
Mirror318 Avatar asked Oct 24 '25 04:10

Mirror318


2 Answers

The ActiveModel::Error class (what you get if you call record.errors) has a details attribute, which is a hash of the attributes and their errors, including the error key.

foo.valid?
=> false
foo.errors.details
=> {:user=>[{:error=>:blank}]}

The ActiveModel source has an en.yml, which will give you the canonical set of keys. The rails-i18n gem includes translations for many of the standard keys, but there are definite gaps (that is, some locales are complete, some are not).

As @Mirror318 says, you can see the set of error message translations for the current locale by running I18n.t 'errors'. If your current locale is en.yml that will be the same as the canonical list; otherwise it is the available set of translated messages.

like image 64
rmlockerd Avatar answered Oct 26 '25 19:10

rmlockerd


In a Rails console, you can enter:

I18n.t 'errors'

And that will return a hash of all current error messages. You can adjust that hash via the locale .yml file

like image 40
Mirror318 Avatar answered Oct 26 '25 17:10

Mirror318