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
|
2014-12-09 09:43:21 +01:00
|
|
|
after_initialize { self.total_price = 0 }
|
2014-12-10 13:21:06 +01:00
|
|
|
after_create :pay_price
|
2014-12-04 19:50:02 +01:00
|
|
|
|
2014-12-10 13:21:06 +01:00
|
|
|
belongs_to :user, counter_cache: true
|
2014-11-25 14:27:27 +01:00
|
|
|
has_many :order_products
|
2015-01-09 19:15:48 +01:00
|
|
|
has_many :products, through: :order_products
|
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
|
2014-12-10 13:21:06 +01:00
|
|
|
validates :order_products, presence: true
|
2014-12-04 19:50:02 +01:00
|
|
|
|
2014-12-05 16:15:07 +01:00
|
|
|
accepts_nested_attributes_for :order_products, reject_if: proc { |op| op[:count].to_i <= 0 }
|
2014-11-25 02:01:57 +01:00
|
|
|
|
2014-12-09 10:57:38 +01:00
|
|
|
def price
|
|
|
|
price = 0
|
2014-12-10 13:21:06 +01:00
|
|
|
order_products.each do |op|
|
|
|
|
price += op.count * op.product.read_attribute(:price)
|
2014-12-09 10:57:38 +01:00
|
|
|
end
|
|
|
|
price
|
|
|
|
end
|
|
|
|
|
2014-12-10 13:21:06 +01:00
|
|
|
private
|
|
|
|
|
|
|
|
def pay_price
|
|
|
|
user.pay(price)
|
|
|
|
end
|
2014-11-09 22:53:39 +01:00
|
|
|
end
|