Transaction scope

I just read this in the documentation and would like to clarify what it
means:

Both Base#save and Base#destroy come wrapped in a transaction that
ensures that whatever you do in validations or callbacks will happen
under the protected cover of a transaction. So you can use validations
to check for values that the transaction depend on or you can raise
exceptions in the callbacks to rollback.

Does this mean that if I do my_model.save I get a Transaction “for free”
without having to declare one?

And, if so, does it follow that I can write code in “before_save” and/or
“after_save” that updates a second model, my_other_model, safe in the
knowledge that either both models will update or neither will?

Many thanks.

John L. wrote:

I just read this in the documentation and would like to clarify what it
means:

Both Base#save and Base#destroy come wrapped in a transaction that
ensures that whatever you do in validations or callbacks will happen
under the protected cover of a transaction. So you can use validations
to check for values that the transaction depend on or you can raise
exceptions in the callbacks to rollback.

Does this mean that if I do my_model.save I get a Transaction “for free”
without having to declare one?

And, if so, does it follow that I can write code in “before_save” and/or
“after_save” that updates a second model, my_other_model, safe in the
knowledge that either both models will update or neither will?

Indeed that is the case. If this behavior is critical to your
application then I also suggest writing the appropriate test cases
(which I recommend either way :wink: to ensure this behavior will persist
over different versions.


Roderick van Domburg
http://www.nedforce.com

Indeed that is the case.
Great, many thanks!

I also suggest writing the appropriate test cases
Yes, you can’t have too many tests!

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs