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.
Michael Glaesemann grzm seespotcode net
[0](Peak Obsession) [1](http://dev.rubyonrails.org/svn/rails/trunk/actionpack/lib/action_controller/session/active_record_store.rb)