Conceptual question:
I have a regular e-commerce application with models Order
, and User
. Order
has a column status
that indicates the status
of the order. In particular, and what's relevant to this question is that status = 0
indicates a cart.
Now while each User has many Orders, each User typically has one Cart.
For this in my User
model, I have defined:
has_many :orders
has_one :cart, -> { where "status = 0" }, class_name: 'Order'
My trouble with this is that my various controllers, I can't use:
cart = my_user.cart || my_user.cart.build
The best that I can hope for is:
cart = my_user.cart || my_user.orders.build(status: 0)
Also the current implementation makes ensuring that only a single cart exists (one order with status 0) difficult. Now I'm relatively new to Rails, and still familiarizing myself with recommended design practices. What's the best way to achieve this functionality in Rails?
Aucun commentaire:
Enregistrer un commentaire