Reputation: 1507
I'm hoping anyone can point me in the right direction as I've been breaking my head around this issue for a couple of days 😩.
A single website lists multiple shops, each with a show page, from which a user can select and add products to a (session) cart. Every shop has a corresponding cart. The user performs an individual checkout process for each cart. On the carts#index page, the user can see an overview of the active carts.
I've found the below snippet to be completely working. Yet, when trying to upgrade the set_cart method to include multiple carts, my own logic and ideas fail.
module CurrentCart
private
def set_cart
@cart = Cart.find(session[:cart_id])
rescue ActiveRecord::RecordNotFound
@cart = Cart.create
session[:cart_id] = @cart.id
end
end
An approach that worked, but isn't very scalable, is to create 1 session cart for the entire website and then send a shop instance to filter down (i.e., @cart.items_for_shop(@shop). The issue is that both a cart instance and a shop instance need to be available everywhere in the app. It would make much more sense to have a separate cart_id for each shop.
How would you approach storing multiple carts in the session?
Many thanks in advance 🙏
Upvotes: 0
Views: 87
Reputation: 10898
I would probably go down the route of having a ParentCart, or MetaCart, or whatever you want to call the thing that all the carts for each shop belong to. Lets go with UberCart
for this example.
So, your set_cart
method finds or creates an UberCart
record, exactly as you currently have for a normal Cart
.
Next, for each shop, either when you create the UberCart
, or maybe later when you view a shop ... up to you, you create a Cart
, which is essentially a join table between your UberCart
and the chosen Shop
.
LineItem
s from the Shop
are then attached to the correct Cart
, which is accessible from the UberCart
in your session.
In your CartController#index
action you can then just use @uber_cart.carts
to access all the carts belonging to this UberCart
.
Upvotes: 1