Controlling the order of rails validations -


i have rails model has 7 numeric attributes filled in user via form.

i need validate presence of each of these attributes easy using

validates :attribute1, :presence => true validates :attribute2, :presence => true # , on through attributes 

however need run custom validator takes number of attributes , calculations them. if result of these calculations not within range model should declared invalid.

on it's own, easy

validate :calculations_ok?  def calculations_ok?   errors[:base] << "not within required range" unless within_required_range? end  def within_required_range?   # check calculations , return true or false here end 

however problem method "validate" gets run before method "validates". means if user leaves 1 of required fields blank, rails throws error when tries calculation blank attribute.

so how can check presence of required attributes first?

i'm not sure it's guaranteed order these validations run in, might depend on how attributes hash ends ordered. may better off making validate method more resilient , not run if of required data missing. example:

def within_required_range?   return if ([ a, b, c, d ].find(&:blank?))    # ... end 

this bail out if of variables a through d blank, includes nil, empty arrays or strings, , forth.


Comments

Popular posts from this blog

c# - how to write client side events functions for the combobox items -

exception - Python, pyPdf OCR error: pyPdf.utils.PdfReadError: EOF marker not found -