2014-12-04 19:50:02 +01:00
|
|
|
# == Schema Information
|
|
|
|
#
|
|
|
|
# Table name: order_products
|
|
|
|
#
|
|
|
|
# id :integer not null, primary key
|
|
|
|
# order_id :integer
|
|
|
|
# product_id :integer
|
|
|
|
# count :integer default(1)
|
|
|
|
#
|
|
|
|
|
2014-11-25 14:27:27 +01:00
|
|
|
class OrderProduct < ActiveRecord::Base
|
2015-01-15 00:39:34 +01:00
|
|
|
after_create :remove_from_stock
|
|
|
|
|
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
|
|
|
|
validates :count, numericality: { greater_than_or_equal_to: 0 }
|
|
|
|
|
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-01-15 00:39:34 +01:00
|
|
|
private
|
|
|
|
|
|
|
|
def remove_from_stock
|
|
|
|
product.stock -= self.count
|
|
|
|
product.save
|
|
|
|
end
|
2014-11-25 14:27:27 +01:00
|
|
|
end
|