我正在编写一个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
答案 0 :(得分:2)
删除
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]