Skip to content

Instantly share code, notes, and snippets.

@stochastic-thread
Created July 19, 2015 22:28
Show Gist options
  • Save stochastic-thread/167781782d20db95237f to your computer and use it in GitHub Desktop.
Save stochastic-thread/167781782d20db95237f to your computer and use it in GitHub Desktop.
class OrderItem < ActiveRecord::Base
belongs_to :product
belongs_to :order
validates :quantity, presence: true, numericality: { only_integer: true, greater_than: 0 }
validate :product_present
validate :order_present
before_save :finalize
def unit_price
if persisted?
self[:unit_price]
else
product.price
end
end
def total_price
unit_price * quantity
end
private
def product_present
if product.nil?
errors.add(:product, "is not valid or is not active.")
end
end
def order_present
if order.nil?
errors.add(:order, "is not a valid order.")
end
end
def finalize
self[:unit_price] = unit_price
self[:total_price] = quantity * self[:unit_price]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment