ruby-on-rails - 验证 Controller 中用户的 admin 属性是否设置为 true 的正确方法是什么?

标签 ruby-on-rails ruby ruby-on-rails-4

我有一个 Devise User 模型,其属性 admin 类型为 bool 值。我如何在我的 Controller 中指定只希望某些操作在 admin = true 时可用?以下授权方法是否有效?

def authorize
redirect_to login_url, alert:"Not authorized" if current_user.admin == false
end

这是我的用户表,admin 是一个 bool 值。

create_table "users", force: true do |t|
t.string   "email",                  default: "",    null: false
t.string   "encrypted_password",     default: "",    null: false
t.string   "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer  "sign_in_count",          default: 0,     null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string   "current_sign_in_ip"
t.string   "last_sign_in_ip"
t.datetime "created_at"
t.datetime "updated_at"
t.boolean  "admin",                  default: false
t.string   "image_file_name"
t.string   "image_content_type"
t.integer  "image_file_size"
t.datetime "image_updated_at"
t.string   "name"
end

current_user 在 authorize_admin 方法中使用 Pry 的输出:

NameError: undefined local variable or method `current_user' for :authorize_admin:Symbol

我正在使用 devise,那么 current_user 不应该工作吗?

这是控制台中 User.first 的输出:

#<User id: 1, email: "email@gmail.com", encrypted_password:    

"$2a$10$RCgzx7PJho4vegbf8Z04eumTGB1RyDl5YvDeCAMz7g3...", reset_password_token: nil,   
 reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 5,   
 current_sign_in_at: "2014-10-25 23:42:17", last_sign_in_at: "2014-10-23 00:57:07", 
 current_sign_in_ip: "127.0.0.1", last_sign_in_ip: "127.0.0.1", created_at:   
 "2014-10-10   
19:24:39", updated_at: "2014-10-25 23:42:17", admin: false, image_file_name: nil,   
image_content_type: nil, image_file_size: nil, image_updated_at: nil, name: nil>

最佳答案

How can I specify in my controllers that only want certain actions to be available if admin = true?

您可以使用 rails before filter实现它。 您可以在应用程序 Controller 中定义您的授权方法,这将使该方法在您的所有 Controller 中可用。

class ApplicationController < ActionController::Base
  private
  def authorize
    redirect_to login_url, alert:"Not authorized" if current_user.try(:admin) == false
  end
end

现在在 Controller 中,您可以为要授权的方法设置前置过滤器。

class HomeController < ApplicationController
  before_action :authorize, only: [:your_action_name]
  def your_action_name
    #some action
  end
end

如果您的代码根据管理员和普通用户进行了大量自定义,那么您也可以使用 cancancan

关于ruby-on-rails - 验证 Controller 中用户的 admin 属性是否设置为 true 的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26563007/

相关文章:

Ruby 匹配第一次出现的字符串以进行 gsub 替换

ruby-on-rails - 删除 ActiveAdmin 生成的注释路由

ruby-on-rails - STI 子类范围的未定义方法错误

ruby-on-rails - 添加/删除 has-many-through 关联的 RESTful 方式

html - 嵌套形式(设计问题)

html - 页眉未触及屏幕顶部

ruby-on-rails - Rails 有标准的正则表达式验证器吗?

iphone - 如何以编程方式连接两个 aac 文件

具有灵活的 gem 依赖关系的 Ruby Gems?

ruby-on-rails - 将 Rails 模型文件组织到子目录中