2014-12-04 18:50:02 +00:00
|
|
|
# == Schema Information
|
|
|
|
#
|
2015-02-09 16:06:24 +00:00
|
|
|
# Table name: order_items
|
2014-12-04 18:50:02 +00:00
|
|
|
#
|
|
|
|
# id :integer not null, primary key
|
2015-03-19 15:22:55 +00:00
|
|
|
# order_id :integer
|
2015-02-09 16:06:24 +00:00
|
|
|
# product_id :integer not null
|
2015-03-19 15:22:55 +00:00
|
|
|
# count :integer default("0")
|
2014-12-04 18:50:02 +00:00
|
|
|
#
|
|
|
|
|
2015-02-09 16:06:24 +00:00
|
|
|
class OrderItem < ActiveRecord::Base
|
2014-11-25 13:27:27 +00:00
|
|
|
belongs_to :order
|
|
|
|
belongs_to :product
|
2014-12-04 16:02:08 +00:00
|
|
|
|
2014-12-04 18:50:02 +00:00
|
|
|
validates :product, presence: true
|
2016-03-01 16:15:29 +00:00
|
|
|
validates :count, presence: true, numericality: { only_integer: true,
|
|
|
|
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 18:50:02 +00:00
|
|
|
|
2015-01-14 23:39:34 +00:00
|
|
|
private
|
|
|
|
|
2015-09-14 18:26:16 +00:00
|
|
|
def remove_from_stock!
|
2015-03-12 12:25:11 +00:00
|
|
|
product.decrement!(:stock, count)
|
2015-02-04 18:03:50 +00:00
|
|
|
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
|
2014-11-25 13:27:27 +00:00
|
|
|
end
|