【问题标题】:Devise/cancan redirect admin issue设计/可以重定向管理问题
【发布时间】:2013-07-02 03:42:17
【问题描述】:

我有一个带有布尔开关的用户模型来指定管理员 t/f。我当前的应用程序控制器:

class ApplicationController < ActionController::Base
  protect_from_forgery

  def after_sign_in_path_for(user)
    if current_user.admin?
        admin_index_path
    else
        dashboard_index_path
    end
  end
end

我当前的管理员控制器:

class AdminController < ApplicationController

    def index
        if current_user.admin?

            admin_index_path
        else

            home_index_path
        end
    end
end

目标当然是只允许管理员用户访问管理员索引页面。当我以管理员身份登录时,重定向工作正常,但是当我以非管理员用户身份导航到 admin_index_path 时,我在 AdminController#index 中出现 NoMethodError 错误(未定义的方法 `admin?' for nil:NilClass)。帮助解决这个问题?我觉得可能有一个更优雅和安全的 CanCan 解决方案,但我还没有找到一个很好的解释来说明如何实现它。想法?提前致谢!

【问题讨论】:

  • 您收到此消息是因为您没有 current_user。它只是指向零。这对我来说似乎很奇怪,因为如果您使用设计,它必须指向用户。你在某处覆盖 current_user 吗?
  • 啊,我想我明白了。我实际上是在尝试导航到管理员路径,而根本没有以任何用户身份登录。这可能就是它抛出该错误的原因。不确定如何处理未登录的用户,因为我不需要登录即可使用该应用程序。想法?

标签: ruby-on-rails devise cancan


【解决方案1】:

使用 before_filter

https://github.com/plataformatec/devise#controller-filters-and-helpers

class AdminController < ApplicationController

 before_filter :authenticate_user!, only: [:index]
 before_filter :is_admin, only: [:index]

 def index
 end

 private

  def is_admin
  if user_signed_in?
   if current_user.admin?
     true
   else
     redirect_to home_index_path
   end
  else
    redirect_to login_path
  end
 end

end

user_signed_in?检查用户是否已登录并 current_user.admin? 访问索引时检查是管理员

def is_admin
 if current_user.nil?
  redirect_to login_path
 else
   if current_user.admin?
     true
   else
     redirect_to home_index_path
   end
 end
end

【讨论】:

    【解决方案2】:

    使用资源而不是使用它更通用

    def after_sign_in_path_for(资源) 如果 current_user.admin? admin_index_path 别的 仪表板索引路径 结尾 结尾 和

    然后放 before_filter :authenticate_user!在指数行动中。它会解决你的问题。 你得到 nil 类错误,因为 current_user 变量未设置为用户未登录。

    【讨论】:

      猜你喜欢
      • 2015-12-03
      • 1970-01-01
      • 1970-01-01
      • 2015-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-23
      相关资源
      最近更新 更多