我试图让 before_filter 处理需要用户登录的操作,但是一定有问题,因为它不是。
我使用一个名为“session_helper.rb”的帮助文件进行登录/注销以及检查用户是否已登录(已签名?)。如果在动作或视图中使用它可以正常工作,但是在将它与 before_filer 一起使用时它不起作用。如果我注销用户并尝试访问“/projects/new”,则可以这样做,但不应该这样做。
我究竟做错了什么?
项目负责人:
class ProjectsController < ApplicationController
before_filter :signed_in?, :except => [:index] // <-- doesn't prevent e.g. the action "new" to be executed
def new
@project = Project.new
@users = (current_user.blank? ? User.all : User.find(:all, :conditions => ["id != ?", current_user.id]))
end
def index
@projects = Project.all
if signed_in? // <-- works as it should
@users_projects = Project.where(:user_id => current_user.id)
end
end
... other actions ...
end
session_helper.rb
module SessionsHelper
def sign_in(user)
cookies.permanent[:remember_token] = user.remember_token
self.current_user = user
end
def signed_in?
!current_user.nil?
end
def current_user=(user)
@current_user = user
end
def current_user
@current_user ||= User.find_by_remember_token(cookies[:remember_token])
end
def sign_out
self.current_user = nil
cookies.delete(:remember_token)
end
end