我是Ruby on Rails的新手,目前想要使用Devise gem来实现身份验证系统。该系统需要只有管理员可以列出用户并创建新用户。(我通过向Devise生成的User模型添加admin布尔字段来添加管理员角色)。我使用Rails 3.2,Ruby 1.9.3和最新的Devise gem。
然而,下面列出的代码无法阻止未经身份验证的用户访问特定操作(索引,新建和创建)。
# users_controller.rb
class UsersController < Devise::RegistrationsController
before_filter :authenticate_user!, only: [:index, :new, :create]
before_filter :is_admin, only: [:index, :new, :create]
def index
end
private
def is_admin
current_user.admin?
end
end
==
# config/routes.rb
App::Application.routes.draw do
root to: 'static_pages#home'
get '/about', to: 'static_pages#about'
devise_scope :user do
get '/users', to: 'users#index'
end
devise_for :users, controllers: { sessions: "sessions", registrations: "users" }
end
authenticate_user!
方法不能正常运行(例如,未经身份验证的用户仍然可以访问 /users
或 /users/sign_up
),但也不会引发任何异常。我查了一些资料,但还是无法解决这个问题,请帮忙。
PS. 对不起,我的英语不好。
更新
感谢所有回答。我将根据指示更新is_admin
使其正常工作。
但主要问题在于,在第一次使用authenticate_user!
过滤器时,未登录的用户便能够通过(并且在is_admin
方法中引发异常,因为此处的current_user将为nil)。
# Here non logged in users does not redirect to sign in page when access to,
# for example, /users or /users/sign_up.
before_filter :authenticate_user!, only: [:index, :new, :create]
很抱歉没有表达清楚。