Agile Web Development with Rails 7: Iteration E2 the add_product method (solved)

The add_product method assumes that the default value for the quantity attribute is 0 when it is nil.

I think the code example for add_product:

	​def​ ​add_product​(product)
​ 	  current_item = line_items.​find_by​(​product_id: ​product.​id​)
​ 	  ​if​ current_item
​ 	    current_item.​quantity​ += 1
​ 	  ​else​
​ 	    current_item = line_items.​build​(​product_id: ​product.​id​)
​ 	  ​end​
​ 	  current_item
​ 	​end​

Should be:

  def add_product(product)
​    ​# replace multiple items for a single product in a cart with a​
​    # single item​
    current_item = line_items.find_by(product_id: product.id)
    if current_item
      if current_item.quantity.nil?
        current_item.quantity = 1
      else
        current_item.quantity += 1
      end
    else
      current_item = line_items.build(product_id: product.id, quantity: 1)
    end
    current_item
  end

When you added the column, a default was supplied. New line items should have a quantity. If not, you have a bug in other places.

Should the migration for line_items quantity default to 0?

No, it should default to one. In prior iterations, the existence of a line item represented an item in the cart. If you had the same product in the cart twice, you would have two line items, each representing a quantity of one.

I forgot the default value in the migration.