Written by Sean Behan on Sun Jun 17th 2012

When you use validations in Rails, db column names are used as 'keys' for error messages. This is usually the preferred way to go about it because this maps nicely to the form fields. However, if you use a virtual attribute this may not be the case. For example, I have a 'password_crypted' field in my users table that I don't want my user to see if they fail to complete the field. Instead of returning "Password crypted cannot be blank" I just want to tell them that a password can't be blank. If you provide a custom ':message' on the validation this won't replace the column name. The solution is to override the "human_attribute_name" class method and map specific column names to the string you want to use instead.

class User < ActiveRecord::Base
  validates_presence_of :password_crypted
  ATTR_NAMES = {:password_crypted => "Password"}
  def self.human_attribute_name(attr)
     ATTR_NAMES[attr.to_sym] || super
  end
end

I found these resources helpful while I was in search for a solution to this problem. http://stackoverflow.com/questions/808547/fully-custom-validation-error-message-with-rails

http://henrik.nyh.se/2007/12/change-displayed-column-name-in-rails-validation-messages


Tagged with..
#active record #override #password #validations #Ruby on Rails

Just finishing up brewing up some fresh ground comments...