From 7db93d86c0d7952bf262ad271ff6ee079e9a762b Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Wed, 1 Jul 2020 15:55:10 -0500 Subject: [PATCH] Add Check If ActiveRecord Update Fails as a rails til --- README.md | 3 +- rails/check-if-activerecord-update-fails.md | 33 +++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 rails/check-if-activerecord-update-fails.md diff --git a/README.md b/README.md index a0c5a1a..a6ea5e5 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ and pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud). -_930 TILs and counting..._ +_931 TILs and counting..._ --- @@ -558,6 +558,7 @@ _930 TILs and counting..._ - [Capybara Page Status Code](rails/capybara-page-status-code.md) - [Cast Common Boolean-Like Values To Booleans](rails/cast-common-boolean-like-values-to-booleans.md) - [Change The Nullability Of A Column](rails/change-the-nullability-of-a-column.md) +- [Check If ActiveRecord Update Fails](rails/check-if-activerecord-update-fails.md) - [Check Specific Attributes On ActiveRecord Array](rails/check-specific-attributes-on-activerecord-array.md) - [Code Statistics For An Application](rails/code-statistics-for-an-application.md) - [Comparing DateTimes Down To Second Precision](rails/comparing-datetimes-down-to-second-precision.md) diff --git a/rails/check-if-activerecord-update-fails.md b/rails/check-if-activerecord-update-fails.md new file mode 100644 index 0000000..ea472d8 --- /dev/null +++ b/rails/check-if-activerecord-update-fails.md @@ -0,0 +1,33 @@ +# Check If ActiveRecord Update Fails + +There are two ways to update an `ActiveRecord` instance (not to mention +[`assign_attributes`](https://api.rubyonrails.org/classes/ActiveModel/AttributeAssignment.html), +[`update_attribute`](https://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-update_attribute), +etc.). + +You can call +[`update`](https://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-update) +and +[`update!`](https://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-update-21). +If the updates would make the record invalid based on the model's validations, +then the update will fail. + +You can tell if `update` failed because it will return `false` (instead of +`true`). + +```ruby +unless book.update(book_params) + log_book_update_failed(id: book.id) +end +``` + +The `update!` version will raise an `ActiveRecord::ActiveRecordError` +exception if the update fails. + +```ruby +begin + book.update!(book_params) +rescue ActiveRecord::ActiveRecordError + log_book_update_failed(id: book.id) +end +```