I have a Transaction object and want to:
- Check if a Cart session exists.
- If yes, associate the Transaction with that Cart’s ID from the session.
- If no, create a new Cart object and assign its ID to a session variable.
The relationship is:
Cart has_many Transactions
Transaction belongs_to Cart
My question is: How do you / What is the best way to create a Cart object and associated session from within the Transaction controller?
I tried something like this in the Transaction new action:
@cart = Cart.new
And, this in the Transaction create action:
@cart = Cart.new(params[:cart])
session[:cart] = @cart.id
But, that doesn’t create a session or Cart object. And, when searching Google I wasn’t able to find documentation on this type of thing. Does anyone know how it is done properly?
… will only instantiate a new Cart but will not persist it into the database. The Cart object needs to be stored in the database if it is to be used across requests.
Use this to persist the Cart object:
or
For this:
… you’ve done the right thing by storing the ID in the session 🙂 But note that you need to fetch this again on every request. So you could add a helper in your
application_controller.rbwith something like:…. which could return a
nilcart.