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_idtoCurrent.user.idafter a record is created - Sets
updated_by_idtoCurrent.user.idafter every update - Skips the assignment if
Current.useris 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.usermust be set in the request lifecycle (e.g., viaApplicationController)- The model's table must have
created_by_idandupdated_by_idcolumns (added by the generator) - A
Usermodel 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