Pages

Friday, December 27, 2013

Access of Current Login user in Model

In  your model put the following code what ever the model is let suppose model is User then.


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

After this now in your application controller do like this.
class ApplicationController < ActionController::Base
    def set_current_user
      User.current = current_user
    end
end
class ApplicationController < ActionController::Base
   before_filter :set_current_user
end
Now you can easily fetch the current_user in models by User.current

No comments:

Post a Comment