diff options
author | Josh Sharpe <josh.m.sharpe@gmail.com> | 2009-08-31 12:50:27 -0500 |
---|---|---|
committer | Joshua Peek <josh@joshpeek.com> | 2009-08-31 12:50:27 -0500 |
commit | 80989437dc1502f9194b0600941b6d70a3efa3b2 (patch) | |
tree | a899f747b89ed6b912ee7218d4f9e01f95fe2d25 /activemodel | |
parent | 57f7308da4dff57639f8e67a830baab358aaa5df (diff) | |
download | rails-80989437dc1502f9194b0600941b6d70a3efa3b2.tar.gz rails-80989437dc1502f9194b0600941b6d70a3efa3b2.tar.bz2 rails-80989437dc1502f9194b0600941b6d70a3efa3b2.zip |
I added this feature so that a Map of changed fields could be retrieved
after a model had been saved. This is useful in the after_save callback
when you need to know what fields changed. At present there is no way
to do this other than have code in the before_save callback that takes
a copy of the changes Map, which I thought was a bit messy.
Example.
person = Person.find_by_name('bob')
person.name = 'robert'
person.changes # => {'name' => ['bob, 'robert']}
person.save
person.changes # => {}
person.previous_changes # => {'name' => ['bob, 'robert']}
person.reload
person.previous_changes # => {}
Signed-off-by: Joshua Peek <josh@joshpeek.com>
Diffstat (limited to 'activemodel')
-rw-r--r-- | activemodel/lib/active_model/dirty.rb | 14 |
1 files changed, 14 insertions, 0 deletions
diff --git a/activemodel/lib/active_model/dirty.rb b/activemodel/lib/active_model/dirty.rb index 624c3647ca..735c61df74 100644 --- a/activemodel/lib/active_model/dirty.rb +++ b/activemodel/lib/active_model/dirty.rb @@ -72,12 +72,26 @@ module ActiveModel changed.inject({}) { |h, attr| h[attr] = attribute_change(attr); h } end + # Map of attributes that were changed when the model was saved. + # person.name # => 'bob' + # person.name = 'robert' + # person.save + # person.previous_changes # => {'name' => ['bob, 'robert']} + def previous_changes + previously_changed_attributes + end + private # Map of change <tt>attr => original value</tt>. def changed_attributes @changed_attributes ||= {} end + # Map of fields that were changed when the model was saved + def previously_changed_attributes + @previously_changed || {} + end + # Handle <tt>*_changed?</tt> for +method_missing+. def attribute_changed?(attr) changed_attributes.include?(attr) |