Taking this snippet from the famous agile web development with rails book (most recent edition):
def create
@cart = current_cart
product = Product.find(params[:product_id])
@line_item = @cart.line_items.build(product: product)
This is for a general ecommerce/depot app, and this function is for the “Add to cart” button for a specific product. Here’s where I’m confused:
I imagined the code being:
@line_item = line_items.build(product: product)
@line_item = line_items.build(cart: @cart)
Basically If a line_item belongs to both a product and a cart, I create those relationships separately.
Also, if the cart doesn’t have any line_items yet, then how can I do @cart.line_items? I understand line_items.build(product: product) will return to me a line_item object (which I save into @line_item), but how does cart.line_items work if there’s no line_items in the cart yet?
In the
Cartmodel, there is most likely ahas_manyassociation with theLineItemmodel calledline_items. Rails will automatically initialize that association with an empty array.You can think of
@cartbeing initialized as:Every time you add call
@cart.line_items.build, think of it as this:Note: This is absolutely not how the actual code works, but you can think of the functional behaviour as the same.