summaryrefslogtreecommitdiff
path: root/app/models/product_cart.rb
blob: d4232cb11b83fab84280715e283fc913c3face4d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# 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