Access session in Helper file ? Rails 3

2020-02-07 06:24发布

问题:

how to get session in helper file?

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

Error

undefined method `[]' for nil:NilClass

app/helpers/users_helper.rb:13:in `is_auth?'
app/controllers/admin_controller.rb:8:in `index'

回答1:

Only Controller can access session.

So, in a nutshell, if you are going to use this method in Controllers only like what is you case, you can define it as ApplicationController's method. Or define it a module and include it in AppplicationController.

class ApplicationController < ActionController::Base
  def auth
  end

  def is_auth?
  end
end

If you want to use the method in both controller and view, just declare them as helper_method

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

  def is_auth?
  end
end

Ref: http://apidock.com/rails/ActionController/Helpers/ClassMethods/helper_method

Another note: In my opinion it's really not worth the time to build auth system from scratch by yourself. The functionalities are not easy but quite general. There are well baked gems such as Devise, Authlogic. Better to use them.