使用Devise Gem添加新管理员问题:需新增两名可查看全量用户的管理员
Hey there! Let's get those two extra admins set up for your Rails app—since you're already using Devise, this should be straightforward. Here's how to add new admins and ensure they have the right permissions to view all users:
1. Create New Admins via Rails Console
This is the quickest way to add admins on the fly:
- Open your terminal and run the Rails console:
rails c - Use these commands to create your two new admins (replace the email and password with your own secure values):
The# First admin admin_one = User.create!( email: 'admin1@yourdomain.com', password: 'StrongPass123!', password_confirmation: 'StrongPass123!', admin: true ) # Second admin admin_two = User.create!( email: 'admin2@yourdomain.com', password: 'AnotherStrongPass456!', password_confirmation: 'AnotherStrongPass456!', admin: true )create!method will throw an error if something goes wrong (like duplicate emails), which helps you catch issues quickly.
2. Use Seed Data for Repeatable Setup
If you want these admins to be created automatically whenever you reset or deploy your database, add them to your seed file:
- Open
db/seeds.rband add:# Create admins (only if they don't already exist) [ { email: 'admin1@yourdomain.com', password: 'StrongPass123!' }, { email: 'admin2@yourdomain.com', password: 'AnotherStrongPass456!' } ].each do |admin_data| User.create!( email: admin_data[:email], password: admin_data[:password], password_confirmation: admin_data[:password], admin: true ) unless User.exists?(email: admin_data[:email]) end - Run the seed command to populate the admins:
rails db:seed
3. Ensure Admins Can View All Users
Now make sure only admins have access to the full user list. Update your UsersController to add a permission check:
class UsersController < ApplicationController # Restrict the index action (where you show all users) to admins only before_action :require_admin, only: [:index] def index @users = User.all # Fetches all users for admins to view end private def require_admin # Redirect non-admins to the home page with an alert unless current_user&.admin? redirect_to root_path, alert: "You don't have permission to view all users." end end end
Adjust the only: [:index] part if you have other actions that should be restricted to admins (like editing or deleting users).
Bonus: Convert Existing Users to Admins
If you want to turn existing regular users into admins instead of creating new ones, run this in the Rails console:
# Find the user by email user = User.find_by(email: 'existing_user@yourdomain.com') # Update their admin status user.update!(admin: true)
内容的提问来源于stack exchange,提问作者Harini

