Authentication using Authlogic 3.4.6 with Rails 4.2.6

In this article, we will see how to get railscast episode 160 to work with Rails 4.2.6 and Authlogic 3.4.6. Add authlogic gem to Gemfile.

gem 'authlogic'

Run bundle. Generate user model.

rails g model user

Change the users migration.

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :username
      t.string :email
      t.string :crypted_password
      t.string :password_salt
      t.string :persistence_token

      t.timestamps null: false

Run the migration.

rake db:migrate

Add authlogic declaration acts_as_authentic to user model.

class User < ActiveRecord::Base

Generate the users controller with new and edit actions.

rails g controller users new edit

Declare users resource in routes.rb.

resources :users

Add the register link application/layout file:

<div id="user_nav">
  <%= link_to "Register", new_user_path %>

Add CSS to position navigation bar in application.scss:

div#user_nav { float: right; font-size: 0.9em; }

Add the following to users/new.html.erb and users/edit.html.erb:

<%= render 'form' %>

The users _form partial is:

<%= form_for @user do |f| %>
    <%= f.label :username %><br />
    <%= f.text_field :username %>
    <%= f.label :email %><br />
    <%= f.text_field :email %>
    <%= f.label :password %><br />
    <%= f.password_field :password %>
    <%= f.label :password_confirmation %><br />
    <%= f.password_field :password_confirmation %>
  <p><%= f.submit "Submit" %></p>
<% end %>

Create user_session.rb in models directory.

class UserSession < Authlogic::Session::Base

Create the user_sessions controller.

rails g controller user_sessions new

Implement the user_sessions controller new, create and destroy actions.

class UserSessionsController < ApplicationController
  def new
    @user_session =

  def create
    session_params = params.require(:user_session).permit!
    @user_session =
      redirect_to root_url, notice: 'Successfully logged in.'
      render :new

  def destroy
    @user_session = UserSession.find

    redirect_to root_url, notice: 'Successfully logged in.'

The user_sessions/new.html.erb is:

<%= form_for @user_session do |form| %>
<div class="formList">
    <%= form.label :username, "Username" %>
    <%= form.text_field :username %>
    <%= form.label :password, "Password" %>
    <%= form.password_field :password %>
    <%= form.submit "Submit" %>
<% end %>

You will now be able to signup, login and logout. You can download the source code for this article from al4.

Related Articles

Ace the Technical Interview

  • Easily find the gaps in your knowledge
  • Get customized lessons based on where you are
  • Take consistent action everyday
  • Builtin accountability to keep you on track
  • You will solve bigger problems over time
  • Get the job of your dreams

Take the 30 Day Coding Skills Challenge

Gain confidence to attend the interview

No spam ever. Unsubscribe anytime.