From 04ab027f246ea2641e344bd2762d893f7324a21b Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Thu, 27 Aug 2020 20:28:47 -0500 Subject: [PATCH] Add Inspect Previous Changes To ActiveRecord Object as a rails til --- README.md | 3 +- ...previous-changes-to-activerecord-object.md | 33 +++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 rails/inspect-previous-changes-to-activerecord-object.md diff --git a/README.md b/README.md index 16b3b83..ea25afe 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). -_949 TILs and counting..._ +_950 TILs and counting..._ --- @@ -589,6 +589,7 @@ _949 TILs and counting..._ - [Get The Column Names For A Model](rails/get-the-column-names-for-a-model.md) - [Hash Slicing](rails/hash-slicing.md) - [Ignore Poltergeist JavaScript Errors](rails/ignore-poltergeist-javascript-errors.md) +- [Inspect Previous Changes To ActiveRecord Object](rails/inspect-previous-changes-to-activerecord-object.md) - [List The Enqueued Jobs](rails/list-the-enqueued-jobs.md) - [Log SQL Queries Executed By ActiveRecord](rails/log-sql-queries-executed-by-activerecord.md) - [Mark A Migration As Irreversible](rails/mark-a-migration-as-irreversible.md) diff --git a/rails/inspect-previous-changes-to-activerecord-object.md b/rails/inspect-previous-changes-to-activerecord-object.md new file mode 100644 index 0000000..5f88dd9 --- /dev/null +++ b/rails/inspect-previous-changes-to-activerecord-object.md @@ -0,0 +1,33 @@ +# Inspect Previous Changes To ActiveRecord Object + +If you modify an ActiveRecord object, before saving it, you can inspect changes +with methods like `changed?` and `_changed?`: + +```ruby +book.title = "The Fifth Season" + +book.changed? #=> true +book.title_changed? #=> true +book.publication_year_changed? #=> false + +book.changes +#=> { "title" => ["Original Title", "The Fifth Season"] } +``` + +After saving an object, it will no longer be in a _dirty_ state and these +methods will have no _changes_ to return. + +If you have a reference to the saved ActiveRecord object, you can look at the +_previous_ changes with methods like `previous_changes` and +`_previously_changed?`: + +```ruby +book.title = "The Fifth Season" +book.save + +book.title_previously_changed? #=> true +book.previous_changes +#=> { "title" => ["Original Title", "The Fifth Season"] } +``` + +[source](https://api.rubyonrails.org/classes/ActiveModel/Dirty.html)