paper_trail
is an excellent gem to track record versions and changes.
You almost never want to reimplement something like it yourself. If you need to log some extra information, you can add them on top.
It comes with a really good README file that holds lots of examples. I'll show you only some of its features here:
-
Setting up a model to track changes
: Just addhas_paper_trail
to it:
class User < ActiveRecord::Base
has_paper_trail
end -
Accessing a previous version
: Sayinguser.previous_version
gives you aUser
instance with the attributes from that previous version. You can also use something likeuser.version_at(10.hours.ago)
. -
Diffing attribute changes
: Access aVersion
directly, likeuser.versions.last
and call itschangeset
:
user.versions.last.changeset
=> { 'first_name' => [ 'Alice', 'Bob' ], 'gender' => [ 'female', 'male' ] } -
Tracking who made the changes
: It usescurrent_user
from your controllers, if present. Awesome!
Check out the documentation for more features.