Devise 的 current_X 辅助方法定义如下:
def current_#{mapping}
@current_#{mapping} ||= warden.authenticate(scope: :#{mapping})
end
其中映射是角色类型。 *
因此,您应该能够使用以下方式访问当前管理员:
current_admin
如果这不起作用,我建议检查以确保该设计已在 Admin 模型上正确实例化,如下所示:
class Admin < ActiveRecord::Base
devise :database_authenticatable # additional attributes, i.e. :trackable, :lockable
end
*来源:https://github.com/plataformatec/devise/blob/master/lib/devise/controllers/helpers.rb第106行
如果您继续遇到此问题,可能值得重新考虑您是否
需要使用不同的模型将管理员和用户分开,而不是通过向用户添加管理属性来简化模型和实现模型。
编辑:
为了让您了解查询管理用户的单个用户表与查询两个表的性能差异有多少可以忽略不计,我为 MySQL 数据库播种(在 XAMPP for OSX 上运行,因此它绝不是经过高度优化的) 有 1000 个用户记录,其中只有 2 个用户将“isAdmin”设置为 true。
使用 SQL 查询(从 1000 个用户的池中选择管理员):
SELECT * FROM `users` WHERE isAdmin = 1
结果:
Showing rows 0 - 1 (2 total, Query took 0.0004 seconds.)
使用 SQL 查询(从 Admin 表中选择 Admins):
SELECT * FROM `administrators`
结果:
Showing rows 0 - 16 (17 total, Query took 0.0003 seconds.)
这绝不是一个非常彻底的例子——它只是为了提供一个关于像这样使用时的最小差异的想法。 Active Record 可能会稍微快一点/慢一点,但我无法想象它与上面的结果会有太大的不同。
就我个人而言,我发现向我的用户模型添加“isAdmin”(或类似)属性更容易,如下所示:
Active Record 迁移 (db\migrate\TIMESTAMP_create_users.rb)
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :username
t.boolean :isAdmin, default: false
...
end
end
end
然后在用户和管理员之间进行过滤,如下所示:
用户,管理员除外
users = User.where(:isAdmin => false)
所有用户
allUsers = User.all
仅限管理员
admins = User.where(:isAdmin => true)