Railscast登录记住我

时间:2012-07-24 20:40:26

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.1

我按照修改后的铁路广播,然后决定使用记忆功能升级我的代码。几乎工作但是当进入登录页面时,我收到以下错误

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 个答案:

答案 0 :(得分: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