User Administration Scaffold for Devise

Here is a quick way to add a user controller and views to a rails app that is using Devise for authentication. First, create the controller and views for the model which Devise created for you. You can do that with the scaffold_controller generator.

rails g scaffold_controller users

Now you’ll have the basic user CRUD abilities.

You’ll need to add a password_confirmation password field to the form if the generator didn’t do it for you. The main problem I’ve encountered is that you always have to type in the password and the confirmation when updating a user model. In order to prevent this you can override the password_required? method in the user model.

def password_required?
  (!password.blank? && !password_confirmation.blank?) || new_record?
end

Another nice thing I like to do is create a rake task to create a new user. This can be used on a new database to create a user to log in with. I created a file called auth.rake in lib/tasks.

namespace :auth  do
  desc "Create first database user"
  task :create_first_user => :environment do
    u = User.new
    u.full_name = "First User"
    u.email = "admin@example.com"
    u.password = "password"
    u.password_confirmation = "password"
    u.save

    puts "You can log in with email: '#{u.email}' and password: '#{u.password}'"
  end
end

You can run the task with the command:

rake auth:create_first_user