Skip to content

Commit 7db93d8

Browse files
committed
Add Check If ActiveRecord Update Fails as a rails til
1 parent 400aebd commit 7db93d8

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ and pairing with smart people at Hashrocket.
99

1010
For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud).
1111

12-
_930 TILs and counting..._
12+
_931 TILs and counting..._
1313

1414
---
1515

@@ -558,6 +558,7 @@ _930 TILs and counting..._
558558
- [Capybara Page Status Code](rails/capybara-page-status-code.md)
559559
- [Cast Common Boolean-Like Values To Booleans](rails/cast-common-boolean-like-values-to-booleans.md)
560560
- [Change The Nullability Of A Column](rails/change-the-nullability-of-a-column.md)
561+
- [Check If ActiveRecord Update Fails](rails/check-if-activerecord-update-fails.md)
561562
- [Check Specific Attributes On ActiveRecord Array](rails/check-specific-attributes-on-activerecord-array.md)
562563
- [Code Statistics For An Application](rails/code-statistics-for-an-application.md)
563564
- [Comparing DateTimes Down To Second Precision](rails/comparing-datetimes-down-to-second-precision.md)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# Check If ActiveRecord Update Fails
2+
3+
There are two ways to update an `ActiveRecord` instance (not to mention
4+
[`assign_attributes`](https://api.rubyonrails.org/classes/ActiveModel/AttributeAssignment.html),
5+
[`update_attribute`](https://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-update_attribute),
6+
etc.).
7+
8+
You can call
9+
[`update`](https://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-update)
10+
and
11+
[`update!`](https://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-update-21).
12+
If the updates would make the record invalid based on the model's validations,
13+
then the update will fail.
14+
15+
You can tell if `update` failed because it will return `false` (instead of
16+
`true`).
17+
18+
```ruby
19+
unless book.update(book_params)
20+
log_book_update_failed(id: book.id)
21+
end
22+
```
23+
24+
The `update!` version will raise an `ActiveRecord::ActiveRecordError`
25+
exception if the update fails.
26+
27+
```ruby
28+
begin
29+
book.update!(book_params)
30+
rescue ActiveRecord::ActiveRecordError
31+
log_book_update_failed(id: book.id)
32+
end
33+
```

0 commit comments

Comments
 (0)