summaryrefslogtreecommitdiff
path: root/app/models
diff options
context:
space:
mode:
Diffstat (limited to 'app/models')
-rw-r--r--app/models/cart.rb4
-rw-r--r--app/models/product_cart.rb9
2 files changed, 12 insertions, 1 deletions
diff --git a/app/models/cart.rb b/app/models/cart.rb
index 996d107..b08fc13 100644
--- a/app/models/cart.rb
+++ b/app/models/cart.rb
@@ -9,7 +9,9 @@ class Cart < ApplicationRecord
def delete_product(product_id)
relation = product_carts.find_by(product_id:, cart_id:)
- relation&.destroy
+ return false if relation.nil?
+
+ relation.destroy and return true
end
def add_product(product_id, quantity)
diff --git a/app/models/product_cart.rb b/app/models/product_cart.rb
index 10d4a4c..eb9cf9f 100644
--- a/app/models/product_cart.rb
+++ b/app/models/product_cart.rb
@@ -5,4 +5,13 @@
class ProductCart < ApplicationRecord
belongs_to :cart
belongs_to :product
+
+ validates :quantity, presence: true, comparison: { greater_than: 0 }
+ validate :sole_product_in_cart
+
+ def sole_product_in_cart
+ return if cart.products.find_by(id: product_id).nil?
+
+ errors.add(:product_id, "cart already has product with id #{product_id}")
+ end
end