Possible enhancement method for ActiveModel::Dirty - object.attributes_was or object.attributes_before_changes.

Hey there,

In our project we have really old self implementation from Rails 2.1 for original record tracking.
Now we were updated to Rails 4.2 and trying to refactor code to use Rails methods instead of custom.

I encountered a problem that I have no way to get the original attributes of the object until they were changed. At the moment, it is possible to view only the original values using changed_attributes method, but a complete list of attributes are not possible to receive.

I’ve implemented patch which extends ActiveModel::Dirty module:

module ActiveModel
module Dirty

def attributes_before_changes



How it works:

u = User.last # => #<User:0x007fa7faf593e0, id: 1, user_name: “test”, user_type_id: 1, params: {:key_1=>“value_1”,:key_2=>“value_2”}
u.user_name = “changed_name” # => “changed_name”
u.user_type_id = 2 # => 2
u.params.merge!(key_1: “changed_value_1”, key_3: “value_3”) # => {:key_1=>“changed_value_1”,:key_2=>“value_2”,:key_3=>“value_3”}

u.attributes # =>{“id”=>1,“user_name”=>“changed_name”,“user_type_id”=>2,“params”=>{:key_1=>“changed_value_1”,:key_2=>“value_2”,:key_3=>“value_3”}}

u.attributes_before_changes # =>{“id”=>1,“user_name”=>“test”,“user_type_id”=>1,“params”=>{:key_1=>“value_1”,:key_2=>“value_2”}}


It’s similar to attributes_before_type_cast method, but returns values as objects (ActiveSupport::TimeWithZone, serialized fields, etc), not like in DB.