A simple and solid concern to track ActiveRecord models attributes changes.
You may want to use PaperTrail or other ActiveRecord versioning libraries for a more thorough usage.
Add this line to your application’s Gemfile:
gem 'historyable'
And then execute
$ bundle install
Generate and run the migration to add the changes
table:
$ rails generate historyable:install
$ rake db:migrate
# db/migrate/create_users.rb
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :first_name
t.string :last_name
end
end
end
# app/models/user.rb
class User < ActiveRecord::Base
include Historyable
has_history :first_name, :last_name
end
And now you can:
u = User.new
u.first_name = 'Philippe'
u.save
u.first_name_history
# => [
{
"attribute_value" => "Philippe",
"changed_at" => Tue, 20 Aug 2013 16:20:00 UTC +00:00
}
]
u.first_name = 'Jean-Philippe'
u.save
u.first_name_history
# => [
{
"attribute_value" => "Jean-Philippe",
"changed_at" => Tue, 20 Aug 2013 16:20:10 UTC +00:00
},
{
"attribute_value" => "Philippe",
"changed_at" => Tue, 20 Aug 2013 16:20:00 UTC +00:00
}
]
It is not possible to directly query attribute values since model attributes tracked by Historyable are serialized in the database.
To overcome this limitation, Historyable also exposes the raw ActiveRecord
polymorphic relation.
u.first_name_history_raw
# => #<ActiveRecord::Relation [#<Change id: nil, object_attribute_value: "Jean-Philippe", created_at: "2013-08-20 16:20:10">], [#<Change id: nil, object_attribute_value: "Philippe", created_at: "2013-08-20 16:20:00">]>
See CONTRIBUTING.md for more details on contributing and running test.
historyable is maintained and funded by hooktstudios.