【发布时间】:2017-03-21 18:27:05
【问题描述】:
我遇到了一个非常简单的 Rails 问题。
我有一个博客控制器,其中包含以下几行:
skip_before_action :check_admin, only: [:index, :show], raise: false
...
private
...
def check_admin
redirect_to(root_path) unless current_user && current_user.admin?
end
我希望行为如下:
如果用户未登录或已登录并且其角色不是管理员,并尝试访问其他操作而不是 :index 和 :show,它应该重定向到根路径。
但是现在,当用户未登录时,它会为每个操作显示用户登录页面,而它允许任何已登录用户的每个操作,甚至不允许管理员用户。
我正在使用 Devise 和 CanCanCan。我的ability.rb 看起来像这样:
def initialize(user)
can :read, :all # allow everyone to read everything
if user && user.admin?
can :access, :rails_admin # only allow admin users to access Rails Admin
can :dashboard # allow access to dashboard
can :manage, :all
end
end
我哪里失败了?
编辑:我将控制器中的操作调用更改为:
before_action :check_admin, except: [:index, :show]
现在,已登录的用户会显示所需的行为,而对于未登录的用户,它仍会针对包括索引和显示在内的每个操作重定向到用户登录页面。
编辑 2:我在 application_controller.rb 中有 before_action :authenticate_user!,而其他一些控制器设置为 skip_before_action :authenticate_user!, :only => [:index]。但在我看来,这不应该干扰博客控制器......
另外,我在config/initializers/rails_admin.rb 中有以下内容:
RailsAdmin.config do |config|
### Popular gems integration
## == Devise ==
config.authenticate_with do
warden.authenticate! scope: :user
end
config.current_user_method(&:current_user)
【问题讨论】:
-
这是对三元运算符的严重滥用。为什么不只是
redirect_to(root_path) unless current_user && current_user.admin? -
@meagar 我试过你的线,结果是一样的
-
这不是一个答案,只是评论
-
我还是用你的台词编辑了这个问题;)
-
你有 before_action :authenticate_user! ?在您的控制器或任何其他设计身份验证调用中? (包括在应用程序控制器中)
标签: ruby-on-rails redirect devise controller action