Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/63.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 自定义用户会话_Ruby On Rails_Authentication - Fatal编程技术网

Ruby on rails 自定义用户会话

Ruby on rails 自定义用户会话,ruby-on-rails,authentication,Ruby On Rails,Authentication,我正在尝试创建一个精简的用户会话系统,并尝试将其建模为类似于authlogic class UserSession attr_accessor :username def initialize(params={}) @username = params[:username] end def new_record? true end def self.find return nil if session[:username].nil?

我正在尝试创建一个精简的用户会话系统,并尝试将其建模为类似于authlogic

class UserSession
  attr_accessor :username

  def initialize(params={})
    @username = params[:username]
  end

  def new_record?
    true
  end

  def self.find
    return nil if session[:username].nil?
    UserSession.new session[:username]
  end

  def save
    session[:username] = username
    session[:username] == username
  end

  def user
    User.find :first, :conditions => { :username => username }
  end

  def destroy
    session[:username] = nil
  end
end

我知道没有密码什么的,但我们暂时把它放在一边。我的问题是,显然,从模型访问会话并不容易,而且形式不好。这让我想知道,如果我不能访问会话,我应该如何将创建用户会话抽象为一个模型?

通常我要做的是创建一个SessionController,它管理用户会话的状态(属性、通过模型处理身份验证等),并使用应用程序中的会话:

class SessionsController < ApplicationController

  def new; UserSession.new; end

  def create
     @user_session = UserSession.new(params)
     if id = @user_session.user
       session[:current_user] = id
       redirect_to session[:last_url]
     else
       session[:current_user] = nil
       render :action => new
     end
  end

end

def destroy
  session[:current_user] = nil
  redirect_to root_path
end
class sessioncontrollernew
结束
结束
结束
def销毁
会话[:当前用户]=无
将\重定向到根\路径
结束
助手(
def current_user;session[:current_user];end
)也可以提供帮助。基本上,UserSession允许您使用form_for和类似的帮助程序,并充当身份验证策略持有者(当您实现时)


希望这可以帮助您开始:)

这与我最后更改的内容类似,而且效果相当好;在这一点上,我只是好奇Authlogic是如何做到这一点的,因为他们似乎没有在控制器中放置任何逻辑。