class User < ActiveRecord::Base def self.current Thread.current[:user] end def self.current=(user) Thread.current[:user] = user end end
As you seen, we add two class methods to User model, User.current to fetch the current user and User.current= to assign the current user. So what you need to do is to assign the current user in User model every request you need a current user. Such as
class ApplicationController < ActionController::Base def set_current_user User.current = current_user end end class PostsController < ApplicationController before_filter :require_user # require_user will set the current_user in controllers before_filter :set_current_user end
Now you can easily fetch the current_user in models by User.current, enjoy it!