views:

433

answers:

4

Hey All,

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?

+4  A: 

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

Gdeglin
+6  A: 

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!

Orion Edwards
+1  A: 

I agree with Orion, never use a validation to modify an object, use a callback like after_save instead.

railsninja
Whoever downvoted this, you need to rethink some things. Validations are for validation. If you disagree please comment and we can see what your theory is.
railsninja
+3  A: 

I agree, you should use callbacks to interact with records. Validations should never modify objects..

If still you find the need to do it.. use

myobject.save_without_validation
Rishav Rastogi