Rails numericality validation trick

Let's assume you have an ActiveRecord model User with an attribute age. We need the age attribute to be a number so we are adding the numericality to true and we also need the user to fill it no matter what, so we add presence to true as follows:

...
  validates :page_title, numericality: true, presence: true
...

After we try to submit a form with the age blank, we are getting two error messages:
Age is not a number
Age can't be blank

What can we do, if we need to display only one message at a time? If we want to display only the "Age can't be blank" when the field is empty and the field "Age is not a number" when the field is not a number but it is filled in with something else?
Here comes the allow_blank to the rescue! You can do the following:
...
  validates :page_title, numericality: {allow_blank: true}, presence: true
...
and now it will display one error message per case. I know it is a bit strange behavior and not so common, but I had to implement it somewhere and it could be done with this little trick. Hope you found it useful.

comments powered by Disqus