3

I have a form object (rails 3) and I am trying to get use config/locales/en.yml for the error messages.

My form object looks like this:

class Users::PasswordAndLoginUpdatingForm
  include Virtus.model

  extend ActiveModel::Naming
  include ActiveModel::Conversion
  include ActiveModel::Validations

  attribute :requested_email_address, String
  validates :requested_email_address, allow_blank: true, format: { with: User::VALID_EMAIL_REGEX }

In my form I have the usual

form_for @form_object ... do |f|

If I pry in and find out what the f.object_name is I get users_password_and_login_updating_form

Finally, my config/locales/en.yml looks like this:

en:
  activemodel:
    errors:
      models:
        users_password_and_login_updating_form:
          attributes:
            requested_email_address:
              invalid: "bar"

The issue I'm having is, I cannot get it to use the internationalization.

patrickdavey
  • 1,966
  • 2
  • 18
  • 25

2 Answers2

6

Well I found out the answer by digging into the source code. The issue I was having that my form object was in a Users::PasswordAndLoginUpdatingForm namespace.

The trick is to use activemodel: as your namespace, but, if you have further namespaces in your models, they're separated with /s.

So, the correct yml looks like this:

en:
  activemodel:
    errors:
      models:
        users/password_and_login_updating_form:
          attributes:
            requested_email_address:
              invalid: "foo"
patrickdavey
  • 1,966
  • 2
  • 18
  • 25
1

Should it be activerecord: not activemodel: in your config/locales/en.yml file?

eggroll
  • 1,049
  • 9
  • 18
  • No, I don't think so as this form does _not_ inherit from ActiveRecord. I did just try it though, and no luck. – patrickdavey Feb 20 '17 at 09:46
  • 1
    Two suggestions: First, if you haven't already, take a look at this - http://api.rubyonrails.org/classes/ActiveModel/Errors.html - particularly the first block of code and the text underneath it which reads "The last three methods are required in your object for Errors to be able to generate error messages correctly and also handle multiple languages." It is Rails 5. Second, check out this - http://stackoverflow.com/questions/17935597/ruby-on-rails-i18n-want-to-translate-custom-messages-in-models - and see if you can get it to work as a custom validation error message. – eggroll Feb 20 '17 at 20:48