now available

now available
Want fresh tech tips in your inbox?

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

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


Tagged w/ #active record #override #password #validationsruby on rails

Apps I've Built

XPath Expression Editor
Practice and improve your XPath skills with XPath Editor
Click to buy on the App Store
Photo Location Changer
Easily change the location on your photos and videos
Click here for more info about the app
Photo Date Changer
Easily change the dates and times on your photos and videos
Click here for more info about the app
English dictionary with notifications so you won't forget what you're studying!
Click here for more info about the app
The app that quizzes and scores you on your vocabulary!
Click here for more info about the app