I want to execute a custom validation before the record is created?
It looks as if this is the right method: before_validation_on_create. For example:
before_validation_on_create :custom_validation
But am not sure. Any help would be appreciated.
I want to execute a custom validation before the record is created?
It looks as if this is the right method: before_validation_on_create. For example:
before_validation_on_create :custom_validation
But am not sure. Any help would be appreciated.
In rails 3
before_validation_on_create :do_something
has been replaced with:
before_validation :do_something, :on => :create
before_validation_on_create hooks happen before validation on create… but they aren't validations themselves.
What you probably want to do is use validate and a private method which adds to the error array. like this:
class IceCreamCone
validate :ensure_ice_cream_is_not_melted, :before => :create
private
def ensure_ice_cream_is_not_melted
if ice_cream.melted?
errors.add(:ice_cream, 'is melted.')
end
end
end
There's a great resource here for information on callbacks and the order they happen in:
http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html