Helper文件中的访问会话? Rails 3

如何在帮助文件中获取会话?

UserHelper.rb

module UsersHelper def self.auth login, password user = Users.where("firstname = :firstname AND password = :password", {:firstname => login, :password => password}) if user != [] return true else return false end end def self.is_auth? level puts @session user = Users.where("firstname = :firstname AND password = :password", {:firstname => @session[:firstname], :password => @session[:password]}) if user != [] return true else return false end end end 

Admin_controller.rb

 class AdminController  "ssssss" end end def auth if params[:send] != nil if UsersHelper.auth params[:firstname], params[:password] session[:firstname] = params[:firstname] session[:password] = params[:password] redirect_to :action => "index" else @error = 1 end end end def exit session.delete(:firstname) session.delete(:password) render :json => session end end 

错误

 undefined method `[]' for nil:NilClass app/helpers/users_helper.rb:13:in `is_auth?' app/controllers/admin_controller.rb:8:in `index' 

只有Controller可以访问会话。

因此,简而言之,如果您将在控制器中使用此方法就像您的情况一样,您可以将其定义为ApplicationController的方法。 或者将其定义为模块并将其包含在AppplicationController中

 class ApplicationController < ActionController::Base def auth end def is_auth? end end 

如果要在控制器和视图中使用该方法,只需将它们声明为helper_method

 class ApplicationController < ActionController::Base helper_method :auth, :is_auth? def auth end def is_auth? end end 

参考: http : //apidock.com/rails/ActionController/Helpers/ClassMethods/helper_method

另一个注意事项:在我看来,真的不值得花时间从头开始构建auth系统。 function并不容易,但非常一般。 有很好的烘焙gem,如Devise,Authlogic。 更好地使用它们。

Interesting Posts