修改before_action

时间:2014-11-24 18:21:04

标签: ruby-on-rails activerecord devise

我的用户模型中有一个admin:boolean字段,如果用户是管理员,他们可以检查我的控制器,然后才可以编辑任何内容。

如何修改before_action :authenticate_user!, only: [:edit]以检查用户是否为管理员?

1 个答案:

答案 0 :(得分:7)

您可以在authenticate_user之后添加另一个将被调用的操作!检查当前用户是否具有管理员权限。

class YourController
  # first call authenticate_user! to check if user is signed in
  before_action authenticate_user!, only: [:edit]
  # if user is signed (current_user exist), check if he is admin
  before_action authenticate_admin!, only: [:edit]

  def authenticate_admin!
    # check if current user is admin
    unless current_user.admin
      # if current_user is not admin redirect to some route
      redirect_to 'some_public_route'
    end
    # if current_user is admin he will proceed to edit action
  end
end
相关问题