class OrderDetail < ActiveRecord::Base
  belongs_to :order
  belongs_to :item

  scope :for_order, ->(order_id) { where(order_id: order_id) }

  before_create do
    # Ensure the ordered quantity can be allocated by the item
    if quantity <= item.current_quantity
      item.current_quantity -= quantity
      item.requested_quantity += quantity
      item.save
    end
  end
end

class OrderDetail < ActiveRecord::Base
  belongs_to :order
  belongs_to :item

  validate :should_update_item_requested_quantity

  scope :for_order, ->(order_id) { where(order_id: order_id) }

  def should_update_item_requested_quantity
    if self.quantity >= 0
      # Update subject item requested quantity.
      item.requested_quantity += self.quantity
      item.save
      return true
    end

    false
  end
end

Add validation to ensure valid order detail creation
Add validation to ensure valid order detail creation

Do not allow order details without a valid quantity
