2014-12-04 19:50:02 +01:00
|
|
|
# == Schema Information
|
|
|
|
#
|
|
|
|
# Table name: orders
|
|
|
|
#
|
|
|
|
# id :integer not null, primary key
|
|
|
|
# user_id :integer
|
|
|
|
# cost :integer
|
|
|
|
# created_at :datetime not null
|
|
|
|
# updated_at :datetime not null
|
|
|
|
#
|
|
|
|
|
2014-11-09 22:53:39 +01:00
|
|
|
class Order < ActiveRecord::Base
|
2015-01-15 00:39:34 +01:00
|
|
|
include ActionView::Helpers::TextHelper
|
|
|
|
|
2014-12-09 09:43:21 +01:00
|
|
|
after_initialize { self.total_price = 0 }
|
2015-02-09 17:06:24 +01:00
|
|
|
after_create { self.user.increment!(:balance_cents, -price) }
|
|
|
|
before_destroy { self.user.increment!(:balance_cents, price) }
|
2014-12-04 19:50:02 +01:00
|
|
|
|
2014-12-10 13:21:06 +01:00
|
|
|
belongs_to :user, counter_cache: true
|
2015-02-09 17:06:24 +01:00
|
|
|
has_many :order_items, dependent: :destroy
|
|
|
|
has_many :products, through: :order_items
|
2014-11-25 14:27:27 +01:00
|
|
|
|
2014-12-09 09:43:21 +01:00
|
|
|
attr_accessor :total_price
|
|
|
|
|
2014-12-04 19:50:02 +01:00
|
|
|
validates :user, presence: true
|
2015-02-09 17:06:24 +01:00
|
|
|
validates :order_items, presence: true, in_stock: true
|
2014-12-04 19:50:02 +01:00
|
|
|
|
2015-02-09 17:06:24 +01:00
|
|
|
accepts_nested_attributes_for :order_items, reject_if: proc { |oi| oi[:count].to_i <= 0 }
|
2014-11-25 02:01:57 +01:00
|
|
|
|
2014-12-09 10:57:38 +01:00
|
|
|
def price
|
2015-02-09 17:06:24 +01:00
|
|
|
self.order_items.map{ |oi| oi.count * oi.product.price_cents }.sum
|
2014-12-09 10:57:38 +01:00
|
|
|
end
|
|
|
|
|
2015-01-15 00:39:34 +01:00
|
|
|
def to_sentence
|
2015-02-09 17:06:24 +01:00
|
|
|
self.order_items.map {
|
|
|
|
|oi| pluralize(oi.count, oi.product.name)
|
2015-01-15 00:39:34 +01:00
|
|
|
}.to_sentence
|
|
|
|
end
|
2015-02-12 14:39:58 +01:00
|
|
|
|
|
|
|
def g_order_items(products, params = {})
|
|
|
|
products.each do |p|
|
|
|
|
if (oi = self.order_items.select { |t| t.product == p }).size > 0
|
|
|
|
oi.first.count = [oi.first.product.stock, oi.first.count].min
|
|
|
|
else
|
|
|
|
self.order_items.build(product: p)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
2014-11-09 22:53:39 +01:00
|
|
|
end
|