-
Notifications
You must be signed in to change notification settings - Fork 4
Your First Admin Resource: AdminUser
This guide assumes you’ve used the default AdminUser model, with Devise.
Start by logging into your admin section at http://localhost:3000/admin. The migration created a user with the credentials [email protected] / password.
Your first step is to generate the section to manage your admin users:
rails generate active_admin:resource AdminUser
This will create an empty file:
#app/admin/admin_users.rb
ActiveAdmin.register AdminUser do
end
Loading http://localhost:3000/admin/admin_users/ will show a pretty noisy default index page. So our first step will be to clean it up:
#app/admin/admin_users.rb
ActiveAdmin.register AdminUser do
index do
column :email
column :current_sign_in_at
column :last_sign_in_at
column :sign_in_count
default_actions
end
end
Check out the documentation for index pages to tweak it some more: http://activeadmin.info/documentation.html#Customizing%20the%20Index%20Page
Now comes the time to create your first real administrator. The “New Admin User” button also leads to a page with too many fields. Let’s simplify it as well:
#app/admin/admin_users.rb
ActiveAdmin.register AdminUser do
#...
form do |f|
f.inputs "Admin Details" do
f.input :email
end
f.buttons
end
end
The current form doesn’t let you create a valid admin user instance because it doesn’t let you specify a password. Instead of forcing administrators to set a dummy password on new admin accounts, and then send an email to the person, we’ll let Devise do it’s thing.
This approach requires that your admin model is devise ... :recoverable
(this is the case by default). We’ll make the password for new admin users optional for when creating a new user and we’ll send the password recovery email to let the new user set his own password:
#app/models/admin_user.rb
after_create { |admin| admin.send_reset_password_instructions }
def password_required?
new_record? ? false : super
end
So when you create a new admin, an email is automatically sent to your new admin. Until the person clicks the link to set his password, it’s impossible to log into the account.
Customizing the show form is left to your discretion :-)
You should add this to your AdminUser Model too if you don’t want to take the risk of deleting the last admin:
#app/models/admin_user.rb
before_destroy :raise_if_last
def raise_if_last
if AdminUser.count < 2
raise "Can't delete last admin user"
end
end