Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do I use save!, create! and update_attributes! in Rails?

I'm trying to figure out when to use the bang! versions for saving and updating records? I've read and heard that you don't need them if you're just saving one record or updating a single attribute, if you're confident nothing should go wrong, or to always use them outside of a controller. I guess I'm paranoid about having multiple things getting saved then something fails then there is incomplete data in the DB. The current Rails project I'm working on is over 50% complete and currently doesn't contain any bangs. I have some custom methods I'm calling in models that update or create multiple records and worry if they should be in some sort of transaction.

Sorry if this seems scattered but I'm just trying to figure how to use the saving capabilities in ActiveRecord correctly and make my life easier and little more stress free in the end. Thanks for your time.

like image 753
CalebHC Avatar asked Nov 19 '09 05:11

CalebHC


People also ask

Does Update_attributes call save?

Use update_attribute to skip validations. update_attribute uses save(false) while update_attributes uses save (which means save(true)). If perform_validation is false while calling save then it skips validation, and it also means that all the before_* callbacks associated with save.

Does Rails create save?

create! creates the object and tries to save it but raises an exception if validations fails, e.g. . new and . save!

What does .save do in Ruby?

The purpose of this distinction is that with save! , you are able to catch errors in your controller using the standard ruby facilities for doing so, while save enables you to do the same using standard if-clauses.


1 Answers

The main difference is how failed saves are handled. When updating an ActiveRecord class the ! version will raise an exception if the record is invalid.

I recommend reading the docs here - http://api.rubyonrails.org/classes/ActiveRecord/Base.html

Using transactions might also be something worth looking into - http://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html

like image 156
Andy Gaskell Avatar answered Sep 19 '22 20:09

Andy Gaskell