If you need to customize the field name for ActiveRecord validation messages, I wrote this quick little include
that allows you to remap column names.
For example, if you have a User
with a name
field and you didn’t like the default “Name cannot be blank.” message, and instead wanted “Your name cannot be blank” you can include this module and use rename_fields :name => 'Your Name'
to rename the column.
The easy way to do this is to overwrite your class’s human_attribute_name
method (see documentation for more info). This is how ActiveRecord looks up your column names.
Since this is kind of a pain to do for every class, and maintain separate column maps, I wrote this quick-and-dirty module that you can include in your class and call rename_fields
.
# small concern that allows you to override the field names for validation messages
#
# Example:
#
# # without concern
# class User < ActiveRecord::Base
# validates :name, presence: true
# end
# # => "Name can't be blank"
#
# # with concern
# class User < ActiveRecord::Base
# include CustomFieldNames
# # use "My name" instead of "Name"
# rename_fields :name => 'My name'
#
# validates :name, presence: true
# end
# # => "My name can't be blank"
#
module CustomFieldNames
extend ActiveSupport::Concern
included do
extend ClassMethods
class_attribute(:_field_name_map){ Hash.new }
end
module ClassMethods
# Example:
# rename_fields :column => 'New Name'
def rename_fields(map = {})
self._field_name_map = map.symbolize_keys
end
# override some error messages to use our custom column names
def human_attribute_name(attribute, options = {})
self._field_name_map[attribute.to_sym] || super
end
end
end