Storing Data Between Sessions

Cookies are useful for keeping track of a piece of information between page changes, but as you may have noticed in Figures 13-3 and 13-5, Rails was already setting a cookie, a session cookie, with each request. Rather than manage cookies yourself, you can let Rails do all of that work and move one step further back from the details. (This example is available in ch13/guestbook012.)

Sessions are a means of keeping track of which user is making a given request. Rails doesn’t know anything specific about the user, except that he has a cookie with a given value. Rails uses that cookie to keep track of users and lets you store a bit of information that survives between page requests.

You can set and retrieve information about the current session from the session object, which is available to your controller and view. Because it’s a better idea in general to put logic into the controller, Example 13-3, which is a new version of the app/controllers/entry_controller.rb file, shows what’s involved in storing an array in the session object, retrieving it, and modifying it to add names to the list. Virtually all of it replaces code that was in Example 13-1, with only the retrieval of the name from the form staying the same.

Example 13-3. Working with an array stored in the session object

class EntryController < ApplicationController def sign_in #get names array from session @names=session[:names] #if the array doesn't exist, make one unless @names @names=[] end #get ...

Get Learning Rails: Live Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.