O'Reilly logo

Ruby Cookbook by Leonard Richardson, Lucas Carlson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

15.8. Creating a Login System

Problem

You want your application to support a login system based on user accounts. Users will log in with a unique username and password, as in most commercial and community web sites.

Solution

Create a users table that contains nonnull username and password fields. The SQL to create this table should look something like this MySQL example:

	use mywebapp_development;
	DROP TABLE IF EXISTS 'users';
	CREATE TABLE 'users' (
	  'id' INT(11) NOT NULL AUTO_INCREMENT,
	  'username' VARCHAR(255) NOT NULL,
	  'password' VARCHAR(40) NOT NULL,
	  PRIMARY KEY ('id')
	);

Enter the main directory of the application and generate a User model corresponding to this table:

	$ ./script/generate model User
	      exists app/models/
	      exists test/unit/
	      exists test/fixtures/
          create app/models/user.rb
	      create test/unit/user_test.rb
	      create test/fixtures/users.yml

Open the generated file app/models/user.rb and edit it to look like this:

	class User < ActiveRecord::Base
	  validates_uniqueness_of :username
	  validates_confirmation_of :password, :on => :create
	  validates_length_of :password, :within => 5..40

	  # If a user matching the credentials is found, returns the User object.
	  # If no matching user is found, returns nil.
	  def self.authenticate(user_info)
	    find_by_username_and_password(user_info[:username],
	                                  user_info[:password])
	  end
	end

Now you've got a User class that represents a user account, and a way of validating a username and password against the one stored in the database.

Discussion

The simple User model given ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required