before_validation an before_validation_on_create

45 views
Skip to first unread message

John Merlino

unread,
Aug 5, 2012, 5:32:29 PM8/5/12
to Ruby on Rails: Talk
I'm not sure what's the difference between before_validation an
before_validation_on_create. Is it that before_validation gets invoked
before a create and update call, whereas the latter just gets invoked
on create call?

Andrew Vit

unread,
Aug 5, 2012, 8:56:20 PM8/5/12
to rubyonra...@googlegroups.com
Yes, exactly. before_validation happens before every validation. That means:

model.valid?
model.save
model.create

before_validation_on_create only happens when saving a new record.

masta Blasta

unread,
Aug 6, 2012, 9:30:00 AM8/6/12
to rubyonra...@googlegroups.com
Andrew Vit wrote in post #1071395:
How do these before validation callbacks work? Are they just simple
function callbacks, or can you return false or errors.add in them to
halt the rest of the record.save code?

--
Posted via http://www.ruby-forum.com/.

Colin Law

unread,
Aug 6, 2012, 9:40:39 AM8/6/12
to rubyonra...@googlegroups.com
Have a look at the Rails Guide on ActiveRecord Validations and
Callbacks. That may answer your questions.

Colin

masta Blasta

unread,
Aug 6, 2012, 2:02:41 PM8/6/12
to rubyonra...@googlegroups.com
Colin Law wrote in post #1071428:
Thanks for the pointer.

Here's the quick answer for future users, from RoR api:


"If the returning value of a before_validation callback can be evaluated
to false, the process will be aborted and Base#save will return false.
If ActiveRecord::Validations#save! is called it will raise a
ActiveRecord::RecordInvalid exception. Nothing will be appended to the
errors object.

...

If a before_* callback returns false, all the later callbacks and the
associated action are cancelled. If an after_* callback returns false,
all the later callbacks are cancelled. Callbacks are generally run in
the order they are defined, with the exception of callbacks defined as
methods on the model, which are called last."
Reply all
Reply to author
Forward
0 new messages