【问题标题】:Devise admin routes设计管理路线
【发布时间】:2015-12-08 16:02:35
【问题描述】:

我有一个设计用户,在里面我有 admin 作为布尔值,默认为 false。如何在我的 ruby​​ on rails 应用程序中修复我的路线,以便它只允许拥有 admin 为 true 的管理员访问某些页面。

更新: 我改变了我得到的第一个答案,说要创建一个 is_admin?我的控制器中的方法并指定哪些操作。但是,当我这样做时,我会得到:

undefined method `admin' for nil:NilClass

更新 2:

产品控制器:

class ProductsController < ApplicationController
  before_action :is_admin?, only: [:edit, :update, :destroy]
  before_action :set_product, only: [:show]

应用控制器:

def is_admin?
  if signed_in?
    redirect_to root_path unless current_user.admin
  end
end

【问题讨论】:

  • 消除你的未定义方法错误将current_user.admin更改为current_user.try(:admin)看来你的signed_in?方法没有检查current_user的存在

标签: ruby-on-rails devise


【解决方案1】:

你不应该在路由文件中这样做,最好的地方是控制器过滤部分。注意 :authenticate_user! 方法在 is_admin? 之前。否则current_user 将为零。

class PagesController < ApplicationController
   before_action :authenticate_user!
   before_action :is_admin?, only: [:action1, :action2]
   ...
  
   private
   
   def is_admin?
     unless current_user.is_admin?
       flash.alert = "Sorry, you don't have permissions to perform this action."
       redirect_to root_path
     end
   end
end

【讨论】:

  • 当用户不是管理员时,我得到 nil:NillClass 的未定义方法 'admin'
  • is_admin? 放入ApplicationController 以便在需要时在另一个控制器上使用,并添加user_signed_in? 条件以检查用户是否签名。
  • @ZehniKhairullah 现在就您的问题显示您的代码和完整的堆栈跟踪,因此我们将对其进行检查。
  • @anonymousxxx 我做到了
  • 检查编辑的答案,你必须添加默认的设计验证方法。
【解决方案2】:

我建议您使用 pundit gem 和策略来处理与授权相关的所有内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-10
    • 1970-01-01
    • 1970-01-01
    • 2018-09-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多