Search code examples
ruby-on-rails-3audit-trailpaper-trail-gem

Storing user_id in the paper_trail versions table


I am using paper trail to audit changes to data and would like to store the user_id of the current user in addition to the "whodunnit" column that paper_trail stores by default.

I had no trouble modifying the versions migration to add the user_id column. But I haven't figured out an easy way to set that column from the various models in my app.

It seems like this should work:

has_paper_trail :meta => { :user_id  => current_user.id
                       }

And, I think it might work if I had access to the current_user in my models. But I don't. After researching how to get access to the current_user in my model, I see there is a philosophical debate here. That's not my question though.

So I'm thinking of using a gem like sentient_user or sentient_model to give me access to the current_user in my models so I can set it with something like the code above.

However, adding these gems seems complicated for the little thing I'm trying to do here. I'm wondering if there is an easier way.

What is the easiest way to add the user_id of the person who took the action to the versions table?


Solution

  • The current_user don't exists in models by itself, it appears from controller. So, standard approach is applicable:

    class ApplicationController < ActionController::Base
      def user_for_paper_trail
        current_user if user_signed_in?
      end
    
      def info_for_paper_trail
        { user_id: current_user.id } if user_signed_in?
      end
    end
    
    # config/initializers/paper_trail.rb
    class Version < ActiveRecord::Base
      attr_accessible :user_id
    end