How to get current_user in model and observer Rails

If you want to log the user who created, updates and delete a object in specific model.There is no default way to fetch the current user in models, current_user is always assigned in controllers (as per authentication plugins, restful_authentication, authlogic and devise).

Found one way, by adding some steps in model/user.rb, we can get the object anywhere(also it’s threadsafe)

Step 1

In your user model, add the following line


class User < ActiveRecord::Base
  def self.current
    Thread.current[:user]
  end
  def self.current=(user)
    Thread.current[:user] = user
  end
end

We have to add class methods to the User model,

Step 2


     User.current to fetch the current user 
     User.current= to assign the current user. 

So what we need to do is to assign the current user in User model every request we need a current user.


class ApplicationController < ActionController::Base
    before_filter :set_current_user

    def set_current_user
      User.current = current_user
    end
end

Now we can easily fetch the current_user in models/observers by User.current


class ActivityObserver < ActiveRecord::Observer
   observe :post

  def after_create(record)
   ## here im using background job sidekiq
   InsertActivities.perform_async("#{User.current.id}") 
  end

end

Hope !!! you have got ur solution.

Advertisements

2 thoughts on “How to get current_user in model and observer Rails

Leave a Reply to Philip Duffney Cancel reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s