You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails ActiveAdmin:如何在AdminUser页面仅显示活跃管理员用户?

嘿,我来帮你搞定这个问题!你现在的ActiveAdmin配置没有对AdminUser的列表做任何筛选,所以会显示所有注册的管理员。要实现只显示当前登录的管理员(或者活跃管理员,我会分别说明),可以用下面的方法:

方法一:仅显示当前登录的管理员(你的初始需求)

最简单的方式是使用ActiveAdmin提供的scope_to方法,它能直接把资源范围限定为当前登录用户:

ActiveAdmin.register AdminUser do
  menu :label => "Profilo", :priority => 4
  permit_params :email, :password, :password_confirmation

  # 关键:限定列表只显示当前登录的管理员
  scope_to :current_admin_user

  index do
    selectable_column
    id_column
    column :email
    column :current_sign_in_at
    column :sign_in_count
    column :created_at
    actions
  end
end

scope_to :current_admin_user会自动帮你把查询条件设置为只返回当前登录的管理员记录,这样index页面就只会显示你自己的信息了。

方法二:如果想显示所有活跃状态的管理员(你后来提到的需求)

假设你的AdminUser模型有一个active布尔字段用来标记用户是否活跃,你可以通过重写scoped_collection来自定义筛选条件:

首先,先确保模型里有对应的字段(如果还没有的话),然后修改ActiveAdmin配置:

ActiveAdmin.register AdminUser do
  menu :label => "Profilo", :priority => 4
  permit_params :email, :password, :password_confirmation, :active # 别忘了添加active到permit_params

  controller do
    def scoped_collection
      # 只返回活跃的管理员用户
      AdminUser.where(active: true)
    end
  end

  index do
    selectable_column
    id_column
    column :email
    column :active # 可以添加这个列来显示活跃状态
    column :current_sign_in_at
    column :sign_in_count
    column :created_at
    actions
  end
end

如果你的模型里已经定义了scope :active, -> { where(active: true) },还可以简化成:

controller do
  def scoped_collection
    AdminUser.active
  end
end

这样就能只显示所有处于活跃状态的管理员了。

另外,如果你同时需要显示当前登录的且活跃的管理员,只需要把两个条件结合起来:

controller do
  def scoped_collection
    AdminUser.where(id: current_admin_user.id, active: true)
  end
end

这样就完美满足你的需求啦!

内容的提问来源于stack exchange,提问作者Bistaff

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:18:04