Search code examples
ruby-on-railsdeviserubygems

audited gem: switch between current_user and current_admin


I am using the gem Audited, for logging any changes done to the model. However I faced a problem, when trying to distinguish changes that are being done by normal user and those being done by Admin. I somehow need to tell Audited to user current_admin method, when current_user is nil, but I can't think of way to do it.


Solution

  • You can specify the method the Audited gem uses to assign user. The relavent bit from the README is below:


    Current User Tracking

    If you're using Audited in a Rails application, all audited changes made within a request will automatically be attributed to the current user. By default, Audited uses the current_user method in your controller.

    class PostsController < ApplicationController
      def create
        current_user # => #<User name: "Steve">
        @post = Post.create(params[:post])
        @post.audits.last.user # => #<User name: "Steve">
      end
    end
    

    To use a method other than current_user, put the following in an intializer:

    Audited.current_user_method = :authenticated_user
    

    In your application_controller.rb you can add a method to check for the nil value in current_user

    def current_user_or_admin
      current_user || current_admin
    end
    

    And in an initializer, something like config/initializers/audited.rb add

    Audited.current_user_method = :current_user_or_admin