2014-12-04 19:50:02 +01:00
|
|
|
# == Schema Information
|
|
|
|
#
|
2015-02-09 17:06:24 +01:00
|
|
|
# Table name: order_items
|
2014-12-04 19:50:02 +01:00
|
|
|
#
|
|
|
|
# id :integer not null, primary key
|
2015-03-19 16:22:55 +01:00
|
|
|
# order_id :integer
|
2015-02-09 17:06:24 +01:00
|
|
|
# product_id :integer not null
|
2015-03-19 16:22:55 +01:00
|
|
|
# count :integer default("0")
|
2014-12-04 19:50:02 +01:00
|
|
|
#
|
|
|
|
|
2015-02-09 17:06:24 +01:00
|
|
|
class OrderItem < ActiveRecord::Base
|
2014-11-25 14:27:27 +01:00
|
|
|
belongs_to :order
|
|
|
|
belongs_to :product
|
2014-12-04 17:02:08 +01:00
|
|
|
|
2014-12-04 19:50:02 +01:00
|
|
|
validates :product, presence: true
|
2015-09-04 16:47:49 +02:00
|
|
|
validates :count, presence: true, numericality: { only_integer: true, greater_than: 0 }
|
2015-02-09 17:06:24 +01:00
|
|
|
|
2015-06-30 22:30:34 +02:00
|
|
|
after_create :remove_from_stock
|
2014-12-04 19:50:02 +01:00
|
|
|
|
2014-12-04 17:02:08 +01:00
|
|
|
accepts_nested_attributes_for :product
|
2015-01-15 00:39:34 +01:00
|
|
|
|
2015-02-04 16:49:19 +01:00
|
|
|
def product_attributes=(attributes)
|
|
|
|
self.product = Product.find(attributes[:id])
|
|
|
|
super
|
|
|
|
end
|
|
|
|
|
2015-03-19 16:22:55 +01:00
|
|
|
def cancel
|
|
|
|
self.product.increment!(:stock, self.count)
|
|
|
|
end
|
|
|
|
|
2015-01-15 00:39:34 +01:00
|
|
|
private
|
|
|
|
|
|
|
|
def remove_from_stock
|
2015-03-12 13:25:11 +01:00
|
|
|
product.decrement!(:stock, count)
|
2015-02-04 19:03:50 +01:00
|
|
|
end
|
2014-11-25 14:27:27 +01:00
|
|
|
end
|