Search code examples
ruby-on-railsrubyruby-on-rails-3ruby-on-rails-3.1

Railscast Login Remember me


i followed the revised railcast and then decided to upgrade my code with a remember feature. Almost work but When going to the login page I get the following error

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

Here my code, maybe i made a little mistake. I did a reset on the database

Customer Controller

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

Session Controller

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'

Application Controller

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

Thanks everyone


Solution

  • My mistake was in the following code

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

    and fixing it by the following

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