Conditional validation using ActiveRecord

ActiveRecord validations are easy, right? But what if you need a validation to happen based on a condition?

One way of doing this is to roll your own validation method like so…

class Account < ActiveRecord::Base
  validate :cancelled?

  def cancelled?
    if condition_is_true
      validates_presence_of :cancellation_reason
    end
  end
end

Effective but a bit clunky. My preferred approach is using ActiveRecord’s with_options as follows…

class Account < ActiveRecord::Base
  with_options :if => :cancelled? do |this|
    this.validates_presence_of :cancellation_reason
  end

  private
  def cancelled?
    # some clever stuff here...
  end
end
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s