You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

21 line
547 B

  1. class Cart < ApplicationRecord
  2. has_many :line_items, dependent: :destroy
  3. def add_product(product)
  4. current_item = line_items.find_by(product_id: product.id)
  5. if current_item
  6. current_item.quantity += 1
  7. else
  8. current_item = line_items.build(product_id: product.id)
  9. end
  10. # QUESTION: What happens if the price change in between to additions?
  11. current_item.price = product.price
  12. current_item
  13. end
  14. def total_price
  15. # QUESTION: How and why? :-D
  16. line_items.to_a.sum { |item| item.total_price }
  17. end
  18. end