abo*_*ond 0 ruby-on-rails devise
我有一个设计用户,里面我有 admin 作为布尔值默认为 false。我如何在我的 ruby on rails 应用程序中修复我的路线,以便它仅允许将 admin 设为 true 的管理员访问某些页面。
更新:我更改了我得到的第一个答案,其中说要创建一个 is_admin?方法并指定我的控制器中的操作。但是,当我这样做时,我得到一个:
undefined method `admin' for nil:NilClass
Run Code Online (Sandbox Code Playgroud)
更新 2:
产品控制器:
class ProductsController < ApplicationController
before_action :is_admin?, only: [:edit, :update, :destroy]
before_action :set_product, only: [:show]
Run Code Online (Sandbox Code Playgroud)
应用控制器:
def is_admin?
if signed_in?
redirect_to root_path unless current_user.admin
end
end
Run Code Online (Sandbox Code Playgroud)
You shouldn't do that in the routes file, the best place to do it's on the controller filtering part. Attention to the :authenticate_user! method being before the is_admin?. Otherwise current_user will be nil.
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
646 次 |
| 最近记录: |