Рельсы 5
Объявить модуль
module Current
thread_mattr_accessor :user
end
Назначить текущего пользователя
class ApplicationController < ActionController::Base
around_action :set_current_user
def set_current_user
Current.user = current_user
yield
ensure
# to address the thread variable leak issues in Puma/Thin webserver
Current.user = nil
end
end
Теперь вы можете ссылаться на текущего пользователя как Current.user
Документация о thread_mattr_accessor
Рельсы 3,4
Доступ к current_user
внутри модели не распространен. При этом, вот решение:
class User < ActiveRecord::Base
def self.current
Thread.current[:current_user]
end
def self.current=(usr)
Thread.current[:current_user] = usr
end
end
Установите атрибут current_user
в around_filter
из ApplicationController
.
class ApplicationController < ActionController::Base
around_filter :set_current_user
def set_current_user
User.current = User.find_by_id(session[:user_id])
yield
ensure
# to address the thread variable leak issues in Puma/Thin webserver
User.current = nil
end
end
Установите current_user
после успешной аутентификации:
def login
if User.current=User.authenticate(params[:username], params[:password])
session[:user_id] = User.current.id
flash[:message] = "Successfully logged in "
redirect_to( :action=>'home')
else
flash[:notice] = "Incorrect user/password combination"
redirect_to(:action=>"login")
end
end
Наконец, обратитесь к current_user
в update_history
из Item
.
class Item < ActiveRecord::Base
has_many :histories
after_create :update_history
def update_history
histories.create(:date=>Time.now, :username=> User.current.username)
end
end