27 lines
671 B
Ruby
27 lines
671 B
Ruby
class OrderPromotionCode < ApplicationRecord
|
|
# Associations
|
|
belongs_to :order
|
|
belongs_to :promotion_code
|
|
|
|
# Validations
|
|
validates :order, presence: true
|
|
validates :promotion_code, presence: true
|
|
|
|
# Callbacks
|
|
after_create :apply_discount
|
|
after_create :increment_promotion_code_uses
|
|
|
|
private
|
|
|
|
def apply_discount
|
|
# Apply the discount to the order
|
|
discount_amount = promotion_code.discount_amount_cents
|
|
order.update!(total_amount_cents: [ order.total_amount_cents - discount_amount, 0 ].max)
|
|
end
|
|
|
|
def increment_promotion_code_uses
|
|
# Increment the uses count on the promotion code
|
|
promotion_code.increment!(:uses_count)
|
|
end
|
|
end
|