簡體   English   中英

Rails before_filter沒有重定向

[英]Rails before_filter not redirecting

我正在編寫一個Rails應用程序,它有一個用於登錄的root_path和一個用戶應該在登錄后重定向到的配置文件路徑,或者如果他們已經登錄並訪問主頁。 我還希望將未登錄的用戶始終重定向到登錄頁面,因此我設置了一個before_filter來嘗試這樣做。 不幸的是,它沒有抓到任何東西。 誰能解釋我做錯了什么?

應用控制器

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

  before_filter :require_login

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

    def require_login
      unless current_user
        redirect_to root_url
      end
    end

    helper_method :current_user, :require_login
end

會話控制器

class SessionsController < ApplicationController
  skip_before_filter :require_login

  def index
    if current_user
      redirect_to profile_path
    end
  end

  def create
    user = User.from_omniauth(env["omniauth.auth"])
    puts(env["omniauth.auth"])
    session[:user_id] = user.id
    redirect_to profile_path
  end

  def show
  end

  def destroy
    session[:user_id] = nil
    redirect_to root_url
  end
end

路線

Fbapp::Application.routes.draw do
  root to: "sessions#index"

  match 'profile', to: 'sessions#show', as: 'profile', via: [:get, :post]
  match "auth/:provider/callback", to: "sessions#create", via: [:get, :post]
  match "auth/failure", to: redirect('/'), via: [:get, :post]
  match 'signout', to: 'sessions#destroy', as: 'signout', via: [:get, :post]
  resources :posts

去掉

 skip_before_filter :require_login

來自SessionsController

目前,對於SessionsController中的所有操作, skip_before_filter會從之前的過濾器鏈中刪除require_login過濾器。 因此,它永遠不會被稱為。

順便說一下,您可以使用:only和:except選項控制操作以跳過過濾器,就像應用過濾器一樣。

skip_before_filter : require_login, :only => [:method_name]

要么

skip_before_filter : require_login, :except => [:method_name]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM