I have the following relations :
Class CartItem belongs_to :cart belongs_to :product Class Product (<=> category) has_many :cart_items Class Cart has_many :cart_items
When someone adds a product to his cart, it creates a line in the CartItem table with cart.id and product.id. I can add et remove a product to a cart on the edit page, it works.
But now I would like to add or remove more than one product to a cart at the same time. I just need an input number field when the customer could put the number we want to add/remove. However, I don't manage to do it because in the edit form, if i put a field called for example "number" (for each product) an error will obviously appear because there is no attribute "number". I should probably add a "field_tag" but how can it work ? Thanks in advance
I work on an eCommerce gem written with Rails called Spree. Here's how we've solved that problem.
We have 4 models:
LineItem. These form the basics of our ordering system. A variant can be considered like a "mutation" of a product. Say you have a TShirt that could come in Red, Green or Blue. The Product is the TShirt, while the colours are the variants.
Variants are linked to Orders by way of LineItems. The LineItem object stores: a
quantity and the current price of the variant, just in case that changes later. You don't want prices changing on users unexpectedly!
The logic for adding an item to the cart is simply a form with a variant_id and a quantity field on the product's page. Here's Spree's version. The controller's action that deals with that form basically takes the variant_id and quantity, and does this:<ol> <li>Checks if an order already exists</li> <li>If an order doesn't exist, creates one</li> <li>Creates a new line item on the order with the quantity and variant_id specified, and stores the price.</li> </ol>
Spree's voodoo around this is a little more complex as we care about inventory levels and so on, but that's the basic gist of it.
When the user goes to view their cart, we present them with a form with all the line items and a quantity numeric field. That form looks like this:
That form works by submitting to
OrdersController#update, and due to the fields in the form being nested attributes, the entire order and its line items are updated suitably.
I hope this helps you!