atom feed2 messages in com.googlegroups.rubyonrails-talkRe: [Rails] Models belonging to the s...
FromSent OnAttachments
Frederick CheungOct 5, 2007 10:40 am 
Pat MaddoxOct 10, 2007 3:55 pm 
Subject:Re: [Rails] Models belonging to the session?
From:Pat Maddox (
Date:Oct 10, 2007 3:55:28 pm

On 10/5/07, Michael Glaesemann <> wrote:

I'm implementing a shopping cart which is stored in the database rather than in the session itself. I'm using ActiveRecordStore for session. (using Edge)

I'd like to have the cart belong_to the session in a normal has_one/ belongs_to relationship, e.g.,

create table cart (cart_id primary key, session_id integer not null unique references sessions);

class Cart < ActiveRecord::Base belongs_to :session end

class Session < ActiveRecord::Base has_one :cart end

Using the How to Change Session Store page on the wiki[0] and the active_record_store.rb documentation[1] as references, I believe I should be able to define a find_cart method that returns the current cart or creates a new one:

# in app/controllers/application.rb def find_cart @cart = @session.model.cart || @session.model.create_cart end

I get a NoMethodError: You have a nil object when you didn't expect it! The error occurred while evaluating nil.model

However, shouldn't there already be a session created when the page is called?

As using @session is deprecated, I've also tried using session.model.cart instead:

def find_cart @cart = session.model.cart || session.model.create_cart end

However, this returns an method missing error:

undefined method `cart' for #<CGI::Session::ActiveRecordStore::Session:0x33752c8>

My guess is that I'm not extending the Session model correctly: however, with Ruby's open classes, I think this should work. It's also interesting to me that the

What am I missing? Thanks for any suggestions or pointers to references.

[0]( [1]( action_controller/session/active_record_store.rb)

Why are you doing it like this? Just create your cart and store the id in the session.

def find_cart @shopping_cart ||= Cart.find(session[:cart_id]) end

def cart=(cart) if !cart.nil? session[:cart_id] = else session[:cart_id] = nil end end

Model objects should not know anything about the session.