BushyMark
BushyMark

Reputation: 3395

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?

Upvotes: 5

Views: 1281

Answers (4)

Rishav Rastogi
Rishav Rastogi

Reputation: 15492

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

Upvotes: 5

nitecoder
nitecoder

Reputation: 5486

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

Upvotes: 3

Orion Edwards
Orion Edwards

Reputation: 123692

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!

Upvotes: 12

Gdeglin
Gdeglin

Reputation: 12618

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

Upvotes: 6

Related Questions