1

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

用户助手.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'
4

1 回答 1

3

只有 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

另一个注意事项:在我看来,自己从头开始构建身份验证系统真的不值得。功能并不简单,但很一般。有成熟的宝石,例如 Devise、Authlogic。更好地使用它们。

于 2013-05-27T14:43:28.067 回答