Session Management

Submitted by Karthikeyan on

Sessions can be used to store data at server side between the multiple requests from the same client.

Exmple #1


In this example counter2 variable value is stored in session variable. It gets incremented on each request.

Controller


class LookController < ApplicationController
  def index
    at
    render :action=>"at"
  end
  def at
    @counter1=1
    if(session[:counter2])
      @counter2=session[:counter2]
      @counter2+=1
      session[:counter2]=@counter2
    else
      @counter2=1
      session[:counter2]=@counter2
    end
  end
end

Viewv


views\look\at.rhtml


<h1>Working with sessions</h1>
<% form_tag :action => "at" do %>
Counter 1 = <%=@counter1%>
<br/>
Counter 2 = <%=@counter2%>
<br/>
<%=submit_tag "submit" %>
<%end%>

Output


Working with sessions
Counter 1 = 1
Counter 2 = 6