# frozen_string_literal: true # ProductCart # quantity: integer class ProductCart < ApplicationRecord belongs_to :cart belongs_to :product validates :quantity, presence: true, comparison: { greater_than: 0 } validate :sole_product_in_cart validate :product_quantity def sole_product_in_cart return if cart.nil? || cart.products.find_by(id: product_id).nil? errors.add(:product_id, "cart already has product with id #{product_id}") end def product_quantity return if product.nil? || product.available_quantity > quantity errors.add(:product_id, 'not enough in existence') end end