Ruby on Rails: How to store and retrieve a MRU item in a cookie

It is convenient to display items that the user has visited recently, MRU (Most Recently Used) items.

Preparation

No special preparation is required.

Database

It is assumed only that you have a database table with an identifying column. In this example, the table is called items.

Model

No model changes are required.

Controller

To store an item in the cookie, add something like the following to your show method:

cookies[:item] = params[:id]

:item is simply a key that should be used consistently when setting or retrieving the value of the cookie. The key will be different for each controller. params[:id] retrieves the identifier of the shown element from the URL.

To retrieve an item from the cookie, add something like the following to your controller. Add it to a particular method that retrieves values for display, or add it to the application controller to make the MRU item always available for display.

if (nil == cookies[:item]) 
  @recentitem = nil
else
  begin
    @recentitem = Item.find(cookies[:item])
  rescue ActiveRecord::RecordNotFound
    @recentitem = nil
  end
end

View

You will need to display the item after it is retrieved by the controller.

<% if (@recentitem) %>
  <%= link_to(@recentitem.name, @recentitem) %>
<% end %>

Tags: Technical

Created at: 27 November 2008 12:11 AM

NO COMMENTS ALLOWED