I have a standard active record model with an attributes that is required:
class Sample < ActiveRecord::Base
has_many :colors
before_validation :grab_colors
validates_presence_of :size
validate :number_of_colors
private
def grab_colors
# grab x number of colors | x = size
end
def number_of_colors
self.errors.add("size","is to large.") if colors.count < size
end
end
My problem is that the grab_colors method requires the size attribute but performs a result that needs to be validated as well. In the case above size is used before it’s presence is validated.
Can I set the instance as invalid and stop the save process after all validation have been made?
I am assuming that you want the
number_of_colorsmethod to run after thegrab_colorsmethod. In that case I would recommend calling both methods in order from avalidatemethod.The validation of size is still handled by
But if you have size then
grab_colorsandnumber_of_colorsrun. Now you won’t need these lines