[Solved] How do I prevent the addition of the same product to the cart [closed]
Add uniqueness validation on Cart.product_id, scoping by Cart.id: class Cart < ApplicationRecord validates :product_id, uniqueness: {scope: :id} end But beware of race conditions. UPDATE: If no actual Cart model add validation to LineItem: class LineItem < ApplicationRecord validates :product_id, uniqueness: {scope: :order_id} end UPDATE 2: refactor add method with find_or_initialize_by: def add @cart.save if @cart.new_record? … Read more