File tree 2 files changed +35
-1
lines changed
2 files changed +35
-1
lines changed Original file line number Diff line number Diff line change @@ -9,7 +9,7 @@ and pairing with smart people at Hashrocket.
9
9
10
10
For a steady stream of TILs, [ sign up for my newsletter] ( https://tinyletter.com/jbranchaud ) .
11
11
12
- _ 930 TILs and counting..._
12
+ _ 931 TILs and counting..._
13
13
14
14
---
15
15
@@ -558,6 +558,7 @@ _930 TILs and counting..._
558
558
- [ Capybara Page Status Code] ( rails/capybara-page-status-code.md )
559
559
- [ Cast Common Boolean-Like Values To Booleans] ( rails/cast-common-boolean-like-values-to-booleans.md )
560
560
- [ 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 )
561
562
- [ Check Specific Attributes On ActiveRecord Array] ( rails/check-specific-attributes-on-activerecord-array.md )
562
563
- [ Code Statistics For An Application] ( rails/code-statistics-for-an-application.md )
563
564
- [ Comparing DateTimes Down To Second Precision] ( rails/comparing-datetimes-down-to-second-precision.md )
Original file line number Diff line number Diff line change
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
+ ```
You can’t perform that action at this time.
0 commit comments