好问题。我在我的项目中使用 Rails Admin 和 Pundit。
我更喜欢将管理模型与用户模型分开。
原因之一是我希望能够从 Rails Admin 中“成为用户”,以便在他们遇到问题时能够为他们提供帮助。当您有单独的用户和管理员模型时,这会更容易做到。
管理模型可以非常简单。生成它rails generate devise Admin
然后在你的config/initializers/rails_admin.rb
add
config.authenticate_with do
warden.authenticate! :scope => :admin
end
config.current_user_method(&:current_admin)
要重定向到正确的配置文件,请将此方法添加到您的 ApplicationController
def after_sign_in_path_for(resource)
if resource.class == Administrator
rails_admin_path
else
# Change profile_path to where you want regular users to go
stored_location_for(resource) || profile_path
end
end
为了防止在从当前用户注销时从当前管理员注销,请在以下位置设置此配置config/initializers/devise.rb
config.sign_out_all_scopes = false
为了解决你的另一个问题,我使用了 CanCan 和 Pundit。我更喜欢 Pundit,因为 CanCan 会针对每个请求评估所有权限。使用 Pundit,仅在需要时检查权限。根据我的经验,Pundit 也更加灵活。