Rails Tips: ActiveRecord Conditional Validation

In my User model, I have to check validation presence of state only for users from Nepal. No need to check validation for the users from other country. For this I have implemented as follows:

class User < ActiveRecord::Base
  validates_presence_of :state, :if => :in_nepal?
  
  private
  def in_nepal?
    country == 'Nepal'
  end
end

Here country is User attribute and it check validation presence of state only if country is Nepal. For other country it doesn’t check validation presence of state.

0Shares

One Comment on “Rails Tips: ActiveRecord Conditional Validation”

Leave a Reply

Your email address will not be published. Required fields are marked *

Enter Captcha Here : *

Reload Image