Ognjen Regoje bio photo

Ognjen Regoje
But you can call me Oggy


I make things that run on the web (mostly).
More ABOUT me and my PROJECTS.

me@ognjen.io LinkedIn

How to set both the user and username in audited gem

#rails #technical

A while ago I was working on the audit log and wanted to store both the user and the name. That way the name remains and can be shown if the user is deleted. The audited gem stores either/or, not both, but it was simple enough to override it.

First, override the model:

# config/initializers/audited.rb
Audited.config do |config|
  config.audit_class = Admin::Audit
end

And in the model:

# app/models/admin/audit.rb
class Admin::Audit < Audited::Audit
  before_save do
    if !::Audited.store[:audited_user].to_s.blank?
      self.username = ::Audited.store[:audited_user]
    else
      self.username = ::Audited.store[:current_user].try!(:call).try(:username)
    end
  end
end

This uses audited’s own mechanism for setting the username in case it’s not already set.