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?
  def in_nepal?
    country == 'Nepal'

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.


Leave a Reply

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

Enter Captcha Here : *

Reload Image