Skip to content

Instantly share code, notes, and snippets.

@sashadev-sky
Last active May 20, 2020 19:11
Show Gist options
  • Save sashadev-sky/4760b7243f5732da6a42538ab1edfbf7 to your computer and use it in GitHub Desktop.
Save sashadev-sky/4760b7243f5732da6a42538ab1edfbf7 to your computer and use it in GitHub Desktop.
# Note: as you will come to see from looking at these notes, you can only use these properties correctly BEFORE SAVE
# If you want to keep track of changes in your model Rails provides "Dirty Objects". E.g. Your model has a 'name' attribute:
my_model = MyModel.last
my_model.changed? # it returns false
# You can Track changes to attributes with my_model.name_changed? accessor
my_model.name # returns "Name"
my_model.name = "New Name"
my_model.name_changed? # returns true
# Access previous value with 'name_was' accessor
my_model.name_was # "Name"
# You can also see both the previous and the current values, using name_change
my_model.name_change #=> ["Name", "New Name"]
changed? #=> Boolean
attribute_changed? #=> Boolean
attribute_was #=> access previous value of attribute
attribute_change #=> array of the previous and current values of the attribute
method | changed? | attribute_changed? | attribute_was | attribute_change
-------------------------------------------------------------------------------------------------------------------------
# return val | Boolean | Booleaan | prev attr val | ary of attr's prev & current val
-------------------------------------------------------------------------------------------------------------------------
example | m = MyModel.first | m.name `[#=> "Name"]`| m.name = "Name3" | m.name = "Name4"
| m.changed? | m.name = "Name2" | m.name_was `[#=> "Name"]` | m.name_change `[#=> ["Name3", "Name4"]]`
| `[#=> false]` | m.name_changed? | m.save! | m.name = "Name5"
| | `[#=> true]` | m.name_was `[#=> "Name3"]` | m.name_change `[#=> ["Name4", "Name5"]]`
| | m.save! | m.name `[#=> "Name3"]` | m.save!
| | m.name_changed? | | m.name_change `[#=> nil]`
| | `[#=> false]` | |# `name_change` updates w/out save unlike
# `name_was` returns the 1st name SINCE THE LAST SAVE no matter how many x overrwrite it | `name_was`. But, becomes nil after save
# until u save the instance again. Then it becomes last val set it to b4 the save. | while `name_was` stays last val b4 save
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment