ActiveRecord Validation Dependencies
If you need to add some custom validation for an ActiveRecord model beyond using the standard validation helpers, there are some things to consider.
For custom validation implement the method inside your ActiveRecord class:
def more_validation #some validation code end
One of the issues I had was I had an attribute not set by the form submission. In this case it was the endtime
attribute. Note starttime
and endtime
are defined in the Event ActiveRecord model.
class Event < ActiveRecord validates_numericality_of :duration validate :more_validation, :if => Proc.new {|a| a.duration} def before_save self.endtime = starttime + duration.minutes end def more_validation endtime = starttime + duration.minutes # duration has been validated so this is ok # do some more validation end end
I set my attribute in the before_save
callback. This code will execute only if validation passes.
Make sure before_save
doesn't return boolean false
as request chain will be halted if a before_filter returns false.
Some use validation callbacks
- after_validation() After all validation procedures are complete
- after_validation_on_create() After validation of new objects
- after_validation_on_update() After validation of existing objects being updated
- before_validation() Before the object is validated
- before_validation_on_create() Before validation of new objects
- before_validation_on_update() Before validation of existing objects being updated
It should be noted, the code in the above validation methods will always be executed REGARDLESS if previous validation method calls have failed or not unless we place a conditional Proc
that checks for dependencies. So this is how you can have validation code that depends on other validation like a form validation helper validates_presence_of
.
Thu, 09 Dec 2010 14:28 Posted in Ruby on Rails
Tags ActiveRecord, dependencies, helpers, on, Rails, Ruby, validation