2012-07-24 119 views
1

我遵循修訂的電視廣播,然後決定使用記憶功能升級我的代碼。幾乎工作,但當進入登錄頁面時出現以下錯誤Railscast登錄記住我

Couldn't find Customer with auth_token = 
Note I change the table from User to Customer 

在這裏我的代碼,也許我犯了一個小錯誤。我做了復位數據庫

客戶控制器

class CustomersController < ApplicationController 
    def new 
    @customer = Customer.new 
    end 

    def create 
    @customer = Customer.new(params[:customer]) 
    if @customer.save 
    session[:customer_id] = @customer.id 
     redirect_to root_url, notice: "Thank you for signing up!" 
    else 
     render "new" 
    end 
    end 

end 

會話控制器

class SessionsController < ApplicationController 
    def new 
    end 
    def create 
    customer = Customer.find_by_email(params[:email]) 
     if customer && customer.authenticate(params[:password]) 
     if params[:remember_me] 
     cookies.permanent[:auth_token] = customer.auth_token 
     else 
     cookies[:auth_token] = customer.auth_token 
     end 
     redirect_to root_url, :notice => "Logged in!" 
    else 
     flash.now.alert = "Invalid email or password" 
     render "new" 
    end 
    end 

    def destroy 
    cookies.delete(:auth_token) 
    redirect_to root_url, :notice => "Logged out!" 
    end 
end 

Route.rb

get 'signup', to: 'customers#new', as: 'signup' 
    get 'login', to: 'sessions#new', as: 'login' 
    get 'logout', to: 'sessions#destroy', as: 'logout' 
    resources :sessions 
    resources :customers  
    root :to => 'sessions#new' 

應用控制器

class ApplicationController < ActionController::Base 
    protect_from_forgery 
    private 

    def authorize 
     redirect_to login_url, alert: "Not authorized" if current_customer.nil? 
    end 

    def current_customer 
     @current_customer ||= Customer.find_by_auth_token!(cookies[:auth_token]) if cookies[:auth_token] 
    end 
    helper_method :current_customer 
end 

謝謝大家

+1

修復它爲什麼不使用設計或auth_logic認證?沒有意義重新創造輪子。 – janders223 2012-07-24 20:48:42

+0

因爲我正在尋找完全控制權,所以我不希望這些gem在我的應用程序中有很大的作用 – Jseb 2012-07-24 20:50:35

+0

第一次自己編寫身份驗證以瞭解更多信息並能夠自定義\定製身份驗證是非常好的。 – 2012-07-24 20:52:06

回答

2

我的錯誤是在下面的代碼

def current_customer 
     @current_customer ||= Customer.find_by_auth_token!(cookies[:auth_token]) if cookies[:auth_token] 
    end 

,並通過以下

def current_customer 
     @current_customer ||= Customer.find_by_auth_token(cookies[:auth_token]) if cookies[:auth_token] 
    end