Skip to main content

Trackable

Overview​

The Trackable concern automatically records which user created or last updated a record by storing references to the User model via created_by_id and updated_by_id columns. It relies on Current.user being set in the request lifecycle.


Quick Start​

1. Include the Concern in Your Model​

class Order < ApplicationRecord
include Trackable
end

2. Run the Generator​

The generator scans all models that include Trackable and creates a single migration for any that are missing the required columns:

rails g cm_admin:add_trackable_columns
rails db:migrate

The generator will output which models and columns are being added, or confirm that everything is already in place:

Found 2 model(s) missing trackable columns:
- Order: missing created_by_id, updated_by_id
- Product: missing updated_by_id

✅ Migration created: db/migrate/20240101120000_add_trackable_columns_to_models.rb
⚙ Run `rails db:migrate`

What It Does​

Once included and migrated, the concern:

  • Sets created_by_id to Current.user.id after a record is created
  • Sets updated_by_id to Current.user.id after every update
  • Skips the assignment if Current.user is not present (e.g., background jobs, seeds)

It also adds delegates so you can access user details directly on the record:

order.created_by_full_name  # => "Jane Doe"
order.created_by_email # => "jane@example.com"
order.updated_by_full_name # => "John Smith"
order.updated_by_email # => "john@example.com"

Requirements​

  • Current.user must be set in the request lifecycle (e.g., via ApplicationController)
  • The model's table must have created_by_id and updated_by_id columns (added by the generator)
  • A User model must exist in the application

Displaying Tracking Info in cm-admin​

You can surface created_by and updated_by on index and show pages like any other column:

cm_admin do
cm_index do
column :created_by_full_name, header: "Created By"
column :updated_by_full_name, header: "Last Updated By"
end

cm_show do
cm_section do
cm_row do
field :created_by_full_name, label: "Created By"
field :updated_by_full_name, label: "Last Updated By"
end
end
end
end