How to apply validation conditionally in Rails? -


class test < activerecord::base   def skip_validation    if self.type == 'a'    # skip validation   else    # notihng.   end  end 

note : in test model, have added validations , callback. need apply these validations if above condition matches.

can use object.save(validates :false)?

you can pass :if option so:

validates_presence_of :password, :if => :something_is_true? 

and :something_is_true method in method can describe logic.

class test < activerecord::base # though never name 'test'   validates_presence_of :password, :if => :should_validate_password?    def should_validate_password     # define logic here     # @ end, should return 'true' or 'false'   end end 

if method through validate instance, belongs instance, can pass method string following:

validates_presence_of :password, if: 'admin?' 

it call admin? on current instance, , if returns true, validate presence of password, , vice versa.


Comments