tap/app/models/order_item.rb

44 lines
1.1 KiB
Ruby
Raw Normal View History

# == Schema Information
#
2015-02-09 16:06:24 +00:00
# Table name: order_items
#
# id :integer not null, primary key
# order_id :integer
2015-02-09 16:06:24 +00:00
# product_id :integer not null
# count :integer default("0")
#
2015-02-09 16:06:24 +00:00
class OrderItem < ActiveRecord::Base
belongs_to :order
belongs_to :product
2014-12-04 16:02:08 +00:00
validates :product, presence: true
2015-09-18 11:20:57 +00:00
validates :count, presence: true, numericality: { only_integer: true,
less_than_or_equal_to: ->(oi) { oi.product.try(:stock) || 100 },
greater_than_or_equal_to: 0 }
2015-02-09 16:06:24 +00:00
2015-09-14 18:26:16 +00:00
before_destroy :put_back_in_stock!
after_create :remove_from_stock!
2014-12-04 16:02:08 +00:00
accepts_nested_attributes_for :product
2015-02-04 15:49:19 +00:00
def product_attributes=(attributes)
2015-09-14 18:26:16 +00:00
self.product = OrderItem.products.select{ |p| p.id == attributes[:id].to_i }.first
2015-02-04 15:49:19 +00:00
super
end
2015-09-14 18:26:16 +00:00
def self.products
@products || Product.all
end
private
2015-09-14 18:26:16 +00:00
def remove_from_stock!
product.decrement!(:stock, count)
end
2015-09-14 15:52:25 +00:00
2015-09-14 18:26:16 +00:00
def put_back_in_stock!
2015-09-14 15:52:25 +00:00
product.increment!(:stock, self.count)
end
end