2011-11-07 30 views
2

我正在通過哈特爾書的9.3.3,並保持陷入未定義方法的章9.3.3的Ruby on Rails的 - 憋屈Hartl的書,sign_in

未定義的方法`sign_in'的SessionsController: 0x00000100c0da90

我知道這是因爲sign_in方法在sessions_helper文件中,而該文件由模型拾取,而不是由控制器拾取。 Hartl書不需要「包含SessionsHelper」這一行。

如果我把在黑客,這我假設我不應該,它就結束了登陸我和其他錯誤未定義的方法CURRENT_USER

下面是代碼

SessionsController.rb

class SessionsController < ApplicationController 

    def new 
    @title = "Sign in" 
    end 

    def create 
    user = User.authenticate(params[:session][:email], 
           params[:session][:password]) 
    if user.nil? 
     flash.now[:error] = "Invalid email/password combo." 
     @title = "Sign in" 
     render 'new' 
    else 
     sign_in user 
     redirect_to user 
    end 

end 

    def destroy 
    end 

和sessions_helper.rb

module SessionsHelper 

    def sign_in(user) 
    cookies.permanent.signed[:remember_token] = [user.id, user.salt] 
    self.current_user = user 
    end 

回答

7

在應用程序控制器中應該有一個「include SessionsHelper」。默認情況下,助手包含在視圖中,但爲了在控制器中使用助手,需要明確包含助手。

+0

謝謝!是的,我不知道我錯過了那個盒子。謝謝! –

0

是不是喲你必須在你的ApplicationController中使用include SessionsHelper? (在本書中許可9.11),然後在其中定義current_user(清單9.14)?

3

如果已經包含SessionsHelper在application_controller並仍然得到這個失敗的測試誤差:

如果你在練習章以前更新規格/支持/ utilities.rb文件。 8,並使用給出的例子,很有可能你創建了「sign_in」方法,但是根據第8章練習中的例子將它命名爲「valid_signin」,而不是列表9.6,它只是簡單的命名爲「sign_in」。希望這可以幫助。

這也是基於第二版。的教程,但仍應適用於我想象的第一。

1

另外值得一提的是,您需要注意不要被SessionsHelper模塊中寫入的sign_in助手和spec/support/utilities.rb文件中寫入的sign_in混淆。同名,但兩個不同的功能。在一個被稱爲測試是(清單9.6)的一個寫在utilities.rb文件,如下所示:

def sign_in(user) 
    visit signin_path 
    fill_in "Email",  with: user.email 
    fill_in "Password", with: user.password 
    click_button "Sign in" 
    #sign in when not using capybara as well 
    cookies[:remember_token] = user.remember_token 
end 
0

我犯的錯誤是,我從來沒有把utilities.rb文件中的一個子文件夾支持