Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

my_object.save(false) doesn't REALLY skip my Active Record validations

So I have been pulling my hair out troubleshooting this bug I have been having, and I finally discovered what was causing it. I had always been under the impression that when I called

@my_model.save(false)

That I would be skipping my ActiveRecord validations. Turns out this is partially true. My objects are saving to the database DESPITE my ActiveRecord validation. My problem exists because one of my validations modifies one of the children models during the validation process (This is a scheduling application for a 24 hours location, therefore when lunches are saved, I check them against the day they are saving, AND the next day as well to make sure the user didn't mean "2am" for an overnight shift.

My Question is this: Is there a way to actually skip my validations and move straight to the database? Is this normal ActiveRecord behavior or should I be diving deeper into my validations? Or am I out of luck and need to re-write my validations?

like image 500
BushyMark Avatar asked Mar 29 '09 22:03

BushyMark


2 Answers

My problem exists because one of my validations modifies one of the children models during the validation process

Fix that, then your problems will go away. Validations should never modify the objects!

like image 147
Orion Edwards Avatar answered Nov 15 '22 09:11

Orion Edwards


You may want to use before_create or another callback to interact with the record prior to saving it to the database rather than trying to do this inside of a validator.

Here is the documentation on ActiveRecord callbacks: http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html

There is also a guide on using callbacks with some details on how to skip them here: http://guides.rubyonrails.org/activerecord_validations_callbacks.html

like image 39
Gdeglin Avatar answered Nov 15 '22 09:11

Gdeglin