Search code examples
validationruby-on-rails-4rails-activerecord

Rails 4 validation message: removes "_id" from message


# model.rb
validates :employee_id, presence: true, uniqueness: true

When left empty, the error message says "Employee can't be blank" when I want it to say "Employee ID can't be blank".

I resolved this by:

# model.rb
validates :employee_id, presence: { message: " ID can't be blank" }, uniqueness: true

which outputs "Employee ID can' be blank".

However, this isn't a really good solution IMO. I would like some means of customizing the entire message, including the attribute prefix.

Is there a simple way to do this?


Solution

  • There are several "correct" ways to go about this, but you definitely shouldn't do it via the validation itself, or by defining your own validation method.

    On a model-by-model level, this is controlled by the class-level human_attribute_name method.

    If you want your model's employee_id field to be a special case where the _id postfix isn't truncated, define that special case by overridding human_attribute_name:

    class MyModel
    
      validates :employee_id, presence: true
    
      def self.human_attribute_name(attr, options = {})
        attr == :employee_id ? 'Employee ID' : super
      end
    end
    

    In broader terms, you can redefine human_attribute_name on ActiveRecord::Base to override handling of all _id attributes, but I doubt you want to do this. Generally, it's a good thing that Rails drops the _id postfix.

    The second (and probably better) mechanism is to simply rely on localization. ActiveRecord ties into your locale YAML files for just about everything. If you want your employee_id field to humanize to Employee ID regardless of language, you'll need to edit your YAML files.

    # config/locales/en.yml
    
    en:
      activerecord:
        attributes:
          employee_id: "Employee ID"