我有一个帮助模块:
module SessionsHelper
@current_user
@current_session
def current_user
@current_user = User.find(cookies[:user_id]) if(cookies[:user_id])
end
def current_session
@current_session = Session.find_by_secret_key(cookies[:session_secret_key])
end
def current_user=(user)
@current_user = user
end
def current_session=(session)
@current_session = session
end
end
和一个控制器:
class SessionsController < ApplicationController
include SessionsHelper
respond_to :json
def create
u = User.find_by_ip(request.remote_ip)
u = User.create({:ip => request.remote_ip}) unless u
s = Session.create
s.admin = u
s.save!
send(:current_user=,u)
send(:current_session=,s)
respond_with s
end
end
请注意我必须如何使用该:send
方法设置当前用户,因为直接在控制器中调用current_user=u
不会这样做。