tap/app/models/order.rb

42 lines
917 B
Ruby
Raw Normal View History

# == 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 21:53:39 +00:00
class Order < ActiveRecord::Base
2014-12-09 08:43:21 +00:00
after_initialize { self.total_price = 0 }
2014-11-25 20:34:29 +00:00
belongs_to :user
has_many :order_products
has_many :products, { through: :order_products} do
def << (product)
if proxy_association.owner.products.include?(product)
proxy_association.owner.order_products.find_by(product: product).increment!(:count, 1)
else
super
end
end
end
2014-12-09 08:43:21 +00:00
attr_accessor :total_price
validates :user, presence: true
2014-12-05 15:15:07 +00:00
accepts_nested_attributes_for :order_products, reject_if: proc { |op| op[:count].to_i <= 0 }
2014-11-25 01:01:57 +00:00
def price
price = 0
products.each do |p|
price += p.price * p.count(self)
end
price
end
2014-11-09 21:53:39 +00:00
end