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

时间:2013-05-27 13:23:02

标签: ruby-on-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 < ApplicationController
  include Rails.application.routes.url_helpers
  def initialization
    @session = session
  end
  def index
     @session = session
    if UsersHelper.is_auth?(2)
      render :text => "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'

1 个答案:

答案 0 :(得分:2)

只有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系统。功能并不容易,但非常一般。有很好的烘焙宝石,如Devise,Authlogic。最好使用它们。