VocabReminder
English dictionary with notifications so you won't forget what you're studying!
Click here for more info about the app
VocabQuiz
The app that quizzes and scores you on your vocabulary!
Click here for more info about the app

Change database column names for form validations in Rails

       

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 w/ #active record #override #password #validationsruby on rails