重定向循环在Rails应用程序 - NoNonsense教程

时间:2015-02-03 07:49:51

标签: ruby-on-rails ruby

我正在浏览No Nosense Guide To Rails中的第二个教程,并且在设置用户身份验证(手动没有设计)之后,一旦我成功登录和退出(在命中注销后启动),我一直收到重定向循环错误)。现在我无法在LocalHost上获取任何页面以进行加载。这是Application Controller,Sessions Controller和我的routes.rb代码:

Rails.application.routes.draw do
  resources :comments

  resources :image_posts

  resources :text_posts

  resources :posts

  resources :users

  get 'signup', to: 'users#new', as: 'signup'

  get 'login', to: 'sessions#new', as: 'login'
  post 'login', to: 'sessions#create'
  get 'logout', to: 'sessions#destroy', as: 'logout'

  root 'posts#index'

sessions_controller.rb

class SessionsController < ApplicationController
    def new
    end

    def create
        user = User.find_by(email: params[:email])
        if user && user.authenticate(params[:password])
            session[:user_id] = user.id
            redirect_to root_url, notice: "Log in Successful!"
        else
            flash.now.alert = "Invalid email or password"
            render "new"
        end
    end

    def destroy
        session[:user_id] = nil
        redirect_to root_url, notice: "Log out successful!"
    end
end

application_controller.rb

class ApplicationController < ActionController::Base
    before_action :authenticate_user!
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception

  private

  def current_user
    if session[:user_id]
        @current_user ||= User.find(session[:user_id])
    end
  end

  helper_method :current_user

  def authenticate_user!
    redirect_to login_path unless current_user
  end

感谢阅读!

1 个答案:

答案 0 :(得分:1)

看起来您甚至在login_path页面上授权用户... 尝试

class SessionsController < ApplicationController
  skip_before_action :authenticate_user!
  #...
end