Last active
October 8, 2023 15:35
-
-
Save kule/9425fb7d4c2a13e556ef to your computer and use it in GitHub Desktop.
Simple User Tracking For Rails
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# (concern) e.g. for Post model | |
module UserTrackable | |
extend ActiveSupport::Concern | |
included do | |
before_create :set_created_by | |
before_save :set_updated_by | |
belongs_to :created_by, class_name: 'User', foreign_key: 'created_by_id' | |
belongs_to :updated_by, class_name: 'User', foreign_key: 'updated_by_id' | |
scope :created_by, ->(user) { where(created_by_id: user.id) } | |
scope :updated_by, ->(user) { where(updated_by_id: user.id) } | |
end | |
protected | |
def set_created_by | |
self.created_by = User.current_user | |
true | |
end | |
def set_updated_by | |
self.updated_by = User.current_user | |
true | |
end | |
end | |
# (concern) e.g. for User model | |
module UserTracker | |
extend ActiveSupport::Concern | |
included do | |
def self.current_user=(user) | |
RequestStore.store[:ut_current_user] = user | |
end | |
def self.current_user | |
RequestStore.store[:ut_current_user] | |
end | |
end | |
end | |
# Save the current user for model access | |
class ApplicationController < ActionController::Base | |
before_action :set_current_user | |
private | |
def set_current_user | |
User.current_user = current_user | |
end | |
end | |
# Example Migration | |
class AddUserTrackingToPost < ActiveRecord::Migration | |
def change | |
add_column :posts, :created_by_id, :integer | |
add_column :posts, :updated_by_id, :integer | |
add_index :posts, :created_by_id | |
add_index :posts, :updated_by_id | |
end | |
end | |
# Gemfile | |
gem 'request_store' | |
# example models | |
class User < ActiveRecord::Base | |
include UserTracker | |
end | |
class Post < ActiveRecord::Base | |
include UserTrackable | |
end | |
Post.first.created_by # => User | |
Post.first.updated_by # => User |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It's great. Thank you. I was thinking to have a separate table to store that information. like audit_log table and have columns
action_name => create/update
record_name => User
record_id => 123
whodunit => 456
this way we do not need to add columns to each new table.