Wednesday, June 3, 2009

Proper use of session

Consider the following scenario, you want to store information about current user. After successful login, you might do this.

user = User.authenticate(params[:user_name], params[:password])
if user
   session[:current_user] = user.attributes
   flash[:notice] = "Email and password do not match."
   redirect_to :controller => "login"

Everything would work as you expected except when you try to change the structure of your session. This would make sessions of online users invalid while they are using your web application. For example, they will feel annoying while they are adding items to their wish lists. Another problem is that you want to make that session invalid after you delete that user account, for example. That won't work because you stored the entire record in his session. The only way to do is to add before_filter in application controller to check the existence of the current user. That would make another job to do it.

The best practice is store only simple data in the session: strings, numbers, and so on. Keep your application objects in the database, and then reference them using their primary keys from the session data.

class ApplicationController < ActionController::Base
   before_filter :get_current_user

   def get_current_user
      @current_user = User.find_by_id(session[:user_id])

Here you can access @current_user everywhere in your application and solve many issues during development.

No comments:

Subscribe in a Reader