ActiveModel Absence Validator [Rails 4 Countdown to 2013]

Posted on

This post is part of a series of 31 Rails 4 articles being released each day in December 2012.

Have you ever wanted to validate something that doesn't exist? Rails 4 is introducing a new validator as part of Active Model, named validates_absence_of.

To use the validator, all you need to do is specify the attribute which should not be set:

class SuperHero
  include ActiveModel::Validations

  attr_accessor :secret_identity

  validates :secret_identity, absence: true

If the a value is set, the error message attached to the attribute would be "must be blank".

Example usage:

super_hero =
# => true
super_hero.secret_identity = 'Hal Jordan'
# => false

This post is by Kevin Faustino. Kevin is the Chief Craftsman of Remarkable Labs and also the founder of the Toronto Ruby Brigade.


comments powered by Disqus