Logging Out, Events and Templates with Action Pack
In this thirteenth part of a multi-part series on the Action Pack library for Rails, you'll learn how to log out a user, clean up the events controller, and more. This article is excerpted from chapter six of the book Beginning Rails: From Novice to Professional, written by Jeffery Allan Hardy, Cloves Carneiro Jr. and Hampton Catlin (Apress; ISBN: 1590596862).
Logging Out, Events and Templates with Action Pack (Page 1 of 2 )
Logging Out a User
The logout action is fairly straightforward. We clear out the :user_id session by setting its value to nil , and then we redirect back to the login action.
session[:user_id] = nil
redirect_to login_url end
This is a good way to clear out a specific session, but sometimes you want to clear the entire session without having to remember which keys to reset. Rails provides the method reset_session to do just that.
We’ve done a lot of work on the users controller so far. Listing 6-14 shows what it should look like at this stage.
Listing 6-14. Actions Added in app/controllers/users_controller.rb
class UsersController < ApplicationController def show @user = User.find(params[:id]) end
def new @user = User.new end
def create @user = User.new(params[:user]) if @user.save
flash[:notice] = 'Thanks for signing up!' redirect_to :controller => 'events', :action => 'index' else render :action => 'new' end end
def edit @user = User.find(params[:id]) end
def update @user = User.find(params[:id]) if @user.update_attributes(params[:user])
flash[:notice] = 'Information updated' redirect_to :action => 'show', :id => @user.id else render :action => 'edit' end end
def login if request.post?
if user = User.authenticate(params[:login], params[:password]) session[:user_id] = user.id redirect_to :controller => 'events', :action => 'index'
else flash[:notice] = 'Invalid login/password combination' end end end