Conditional Validation

September 16th, 2009

How do you confirm the presence of one attribute or another? In other words, what if you want to validate that either one of two fields exists? You use Conditional Validation!

So, I need to validate that a user has a login and then also has either an email address or a twitter id. Here’s how I solved it:

class User < ActiveRecord::Base
  validates_presence_of     :login
  validates_presence_of     :email, :unless => :twitter_account?

  def twitter_account?
    !twitter_id.nil?
  end
end

The :if condition also takes a Proc object, but having it call a method is cleaner and easier to extend. And it can be shared across multiple validations or ipossibly used in other situations.

Entry Filed under: Ruby on Rails

Leave a Comment

Required

Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed


RSS Berkman Gender & Tech

RSS Tweets

Tags

Meta