简体   繁体   中英

How to apply validation conditionally in Rails?

class Test < ActiveRecord::Base

 def skip_validation

  if self.type == 'A'
   # skip all validation
  else
   # Do notihng.
  end

end

Note : In my test model, I have added validations and callback. I need to apply these validations only if above condition matches.

Can I use object.save(validates :false) ?

You can pass an :if option to do so:

validates_presence_of :password, :if => :something_is_true?

And :something_is_true is a method actually in your method where you can describe your logic.

class Test < ActiveRecord::Base # Though I would never name it 'Test'
  validates_presence_of :password, :if => :should_validate_password?

  def should_validate_password
    # define your logic here
    # at the end, it should return 'true' or 'false'
  end
end

If the method through which you would like to validate the instance, belongs to the instance, then you can pass that method as a string like following:

validates_presence_of :password, if: 'admin?'

It would call admin? on the current instance, and if it returns true , it will validate the presence of password, and vice versa.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM