2013-05-27 37 views
1

如何在幫助文件中獲取會話?在幫助文件中訪問會話? 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' 
+0

請做到這一點,你違反了MCV彭定康。 –

+0

如何更好地做? – user2425138

+0

模型不可用會話 – user2425138

回答

2

只有Controlle r可以訪問會話。因此,簡而言之,如果您要在控制器中使用此方法,只需要就像您的情況一樣,您可以將其定義爲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。更好地使用它們。

+0

如何寫入助手文件或新類? 'helper_method:auth,:is_auth? def auth end def is_auth? 結束' – user2425138

+0

@ user2425138,'helper_method'將公開這些方法來查看,然後你可以在視圖中使用它們作爲助手。如果僅用於控制器,不需要公開,所有控制器都繼承了ApplicationController並可以使用這些方法。 –

+0

我剛剛閱讀了一篇相關文章(http://stackoverflow.com/questions/20715425/rails-3-2-session-variable-gets-lost-in-view-helper-method),並使用我的rails4應用程序進行了檢查。我在訪問視圖或助手時沒有問題,即'session [:user_id]'? – phoet