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

Ubuntu 11.04 RVM Gem Problem

I recently encountered this issue when using Ubuntu 11.04 to set up a new Rails server with RVM, Passenger, Apache. The first indication of a problem is when you see this line at the end of the rvm install 1.9.2 output:

ruby-1.9.2-p180 - #importing default gemsets (/home/user/.rvm/gemsets/)
'gem' command not found, cannot select a gemset.
Install of ruby-1.9.2-p180 - #complete

This means it had issues compiling ruby, rubygems in particular. You will also notice this error when using the gem command to install any gems:

ERROR:  Loading command: install (LoadError)
no such file to load -- zlib
ERROR:  While executing gem ... (NameError)
uninitialized constant Gem::Commands::InstallCommand

To fix this you’ll have to install the zlib libraries with the command:

sudo apt-get install libghc6-zlib-dev

This won’t fix the problem immediately, you’ll have to rebuild ruby by using:

rvm install 1.9.2

Then you’ll be able to properly install any gems you require.