Selectively track changes made on your ActiveRecord models

Context

There are times when you need to have a history of changes made on key entities in the database in Rails.

There are few tools already for this such as audited. However, audited is tracking every change made on the model that it has been plugged into.

In our case, we did not need to create unnecessary audits. We wanted to selectively track changes on records where we found it crucial to have the history.

Welcome ActsAsTracked

Plug ActsAsTracked into your Rails projects where you are using ActiveRecord as ORM and enjoy minimalist tracking.

If you would like to track changes of Post model, you would need to call acts_as_tracked in it.

  class Post < ApplicationRecord
    acts_as_tracked

    # You may optionally pass in exluded_activity_attributes
    # as an argument to not track given fields.
    #
    # acts_as_tracked(exclude_activity_attributes: %i[:api_key, :username])
  end

Now, you are able to track changes on Post.

@post = Post.first

Post.tracking_changes(actor: User.find(1)) do
  @post.update(
    content: 'New Content'
  )  
end

See activities:

@post.activities

> [#<ActsAsTracked::Activity:0x0000561f330b9cf0
  id: 1,
  actor_id: 1,
  actor_type: "User",
  subject_id: 2,
  subject_type: "Post",
  parent_id: nil,
  parent_type: nil,
  attribute_changes: {"content"=>["Great post content.", "New Content"]},
  activity_type: "updated",
  human_description: nil,
  created_at: Thu, 25 Jun 2020 12:03:39 UTC +00:00,
  updated_at: Thu, 25 Jun 2020 12:03:39 UTC +00:00>]

Documentation

Please, refer to github repository here for full documentation.

Example project

I have also created an example Rails 6 project with the usage here which you can refer to.

Credits

Most of the work has been done by @rogercampos and @camaloon team.

I have packaged, twitched a few things and published it.

Hope you find it useful and in case of questions, hit me up with a message.