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
end

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

Example usage:

super_hero = SuperHero.new
super_hero.valid?
# => true
super_hero.secret_identity = 'Hal Jordan'
super_hero.valid?
# => false
002

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


Comments

comments powered by Disqus