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
class Cart < ActiveRecord::Base
class Session < ActiveRecord::Base
Using the How to Change Session Store page on the wiki and the active_record_store.rb documentation 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
@cart = @session.model.cart || @session.model.create_cart
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:
@cart = session.model.cart || session.model.create_cart
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.
grzm seespotcode net