Skip to content

Commit 04ab027

Browse files
committed
Add Inspect Previous Changes To ActiveRecord Object as a rails til
1 parent 613fc5d commit 04ab027

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
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-
_949 TILs and counting..._
12+
_950 TILs and counting..._
1313

1414
---
1515

@@ -589,6 +589,7 @@ _949 TILs and counting..._
589589
- [Get The Column Names For A Model](rails/get-the-column-names-for-a-model.md)
590590
- [Hash Slicing](rails/hash-slicing.md)
591591
- [Ignore Poltergeist JavaScript Errors](rails/ignore-poltergeist-javascript-errors.md)
592+
- [Inspect Previous Changes To ActiveRecord Object](rails/inspect-previous-changes-to-activerecord-object.md)
592593
- [List The Enqueued Jobs](rails/list-the-enqueued-jobs.md)
593594
- [Log SQL Queries Executed By ActiveRecord](rails/log-sql-queries-executed-by-activerecord.md)
594595
- [Mark A Migration As Irreversible](rails/mark-a-migration-as-irreversible.md)
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# Inspect Previous Changes To ActiveRecord Object
2+
3+
If you modify an ActiveRecord object, before saving it, you can inspect changes
4+
with methods like `changed?` and `<attr>_changed?`:
5+
6+
```ruby
7+
book.title = "The Fifth Season"
8+
9+
book.changed? #=> true
10+
book.title_changed? #=> true
11+
book.publication_year_changed? #=> false
12+
13+
book.changes
14+
#=> { "title" => ["Original Title", "The Fifth Season"] }
15+
```
16+
17+
After saving an object, it will no longer be in a _dirty_ state and these
18+
methods will have no _changes_ to return.
19+
20+
If you have a reference to the saved ActiveRecord object, you can look at the
21+
_previous_ changes with methods like `previous_changes` and
22+
`<attr>_previously_changed?`:
23+
24+
```ruby
25+
book.title = "The Fifth Season"
26+
book.save
27+
28+
book.title_previously_changed? #=> true
29+
book.previous_changes
30+
#=> { "title" => ["Original Title", "The Fifth Season"] }
31+
```
32+
33+
[source](https://api.rubyonrails.org/classes/ActiveModel/Dirty.html)

0 commit comments

Comments
 (0)