diff options
author | HombreLaser <sebastian-440@live.com> | 2023-04-06 14:22:22 -0600 |
---|---|---|
committer | HombreLaser <sebastian-440@live.com> | 2023-04-06 14:22:22 -0600 |
commit | fc191f53503629087fd453e626ec2a4c58e0a21b (patch) | |
tree | aa6fa09f35b62cc302245832e0995a274de32a0a /app | |
parent | b7455b581022059a87633864c2ac2751b035e1e1 (diff) |
AƱadidos validadores
Diffstat (limited to 'app')
-rw-r--r-- | app/controllers/api/carts_controller.rb | 19 | ||||
-rw-r--r-- | app/models/cart.rb | 4 | ||||
-rw-r--r-- | app/models/product_cart.rb | 9 |
3 files changed, 20 insertions, 12 deletions
diff --git a/app/controllers/api/carts_controller.rb b/app/controllers/api/carts_controller.rb index c33f76e..0e14c17 100644 --- a/app/controllers/api/carts_controller.rb +++ b/app/controllers/api/carts_controller.rb @@ -10,24 +10,21 @@ module Api end def create - product_cart = @cart.product_carts.new(product_id: permitted_params[:product_id], - quantity: permitted_params[:quantity]) + product_cart = @cart.add_product(permitted_params[:product_id], permitted_params[:quantity]) - if product_cart.save + if product_cart.errors.empty? render json: serialized_object.serializable_hash, status: :ok else - render json: { errors: product_cart.as_json }, status: :unprocessable_entity + render json: { errors: product_cart.errors.as_json }, status: :unprocessable_entity end end def destroy - product = @cart.product_carts.products.find_by(public_id: params[:id]) - - render status: :not_found and return if product.nil? - - @cart.product_carts.find_by(cart_id: @cart.id, product_id: product.id).destroy - - render status: :no_content + if @cart.delete_product(product.id) + render status: :no_content + else + render status: :not_found + end end private 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 |