# Userstamps

> Automatically recording created_by and updated_by user IDs on ActiveRecord models

- Author: Curtis Miller
- Published: 2007-07-05
- Categories: rails, how-to
- Canonical URL: https://millarian.com/posts/userstamps/

In my [last article](https://millarian.com/posts/migration-timestamps-with-deleted_at-magic-field/) I talked about adding a `deleted_at` field to the migration `timestamps` method for use with acts\_as\_paranoid. One of the additional things I wanted to do was not only capture the timestamp information, but also the user information. This way, I can be really paranoid and see who did what when. To add userstamps, I did the following.

## lib/userstamps.rb

```ruby
module ActiveRecord
  module Userstamp
    def self.included(base) #:nodoc:
      base.class_eval do
        alias_method_chain :create, :userstamps
        alias_method_chain :update, :userstamps

        def current_user
          Thread.current['user']
        end
      end
    end

  private
    def create_with_userstamps #:nodoc:
      user = current_user
      if not user.nil?
        write_attribute('created_by', user.id) if respond_to?(:created_by) and created_by.nil?
        write_attribute('updated_by', user.id) if respond_to?(:updated_by) and updated_by.nil?
      end
      create_without_userstamps
    end

    def update_with_userstamps #:nodoc:
      user = current_user
      write_attribute('updated_by', user.id) if respond_to?(:updated_by) and (not user.nil?)
      update_without_userstamps
    end
  end
end
```

## config/environment.rb (add)

```ruby
require 'userstamp'
ActiveRecord::Base.class_eval do
  include ActiveRecord::Userstamp
end
```
