tap/app/models/order_item.rb

38 lines
835 B
Ruby
Raw Normal View History

# == Schema Information
#
2015-02-09 17:06:24 +01:00
# Table name: order_items
#
# id :integer not null, primary key
2015-02-09 17:06:24 +01:00
# order_id :integer not null
# product_id :integer not null
# count :integer default(0)
#
2015-02-09 17:06:24 +01:00
class OrderItem < ActiveRecord::Base
belongs_to :order
belongs_to :product
2014-12-04 17:02:08 +01:00
validates :product, presence: true
2015-02-09 17:06:24 +01:00
validates :count, numericality: { only_integer: true, greater_than_or_equal_to: 0 }
after_create :remove_from_stock
before_destroy :put_back_in_stock
2014-12-04 17:02:08 +01:00
accepts_nested_attributes_for :product
2015-02-04 16:49:19 +01:00
def product_attributes=(attributes)
self.product = Product.find(attributes[:id])
super
end
private
def remove_from_stock
2015-02-09 17:06:24 +01:00
product.increment!(:stock, - self.count)
end
def put_back_in_stock
2015-02-09 17:06:24 +01:00
product.increment!(:stock, self.count)
end
end