Created
July 19, 2015 22:28
-
-
Save stochastic-thread/167781782d20db95237f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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