tap/app/models/order.rb

39 lines
948 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 22:53:39 +01:00
class Order < ActiveRecord::Base
include ActionView::Helpers::TextHelper
2014-12-09 09:43:21 +01:00
after_initialize { self.total_price = 0 }
after_create { self.user.pay(price) }
belongs_to :user, counter_cache: true
has_many :order_products
has_many :products, through: :order_products
2014-12-09 09:43:21 +01:00
attr_accessor :total_price
validates :user, presence: true
validates :order_products, presence: true, in_stock: true
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
def price
2015-02-04 17:05:02 +01:00
self.order_products.map{ |op| op.count * op.product.price_cents }.sum
end
def to_sentence
self.order_products.map {
|op| pluralize(op.count, op.product.name)
}.to_sentence
end
2014-11-09 22:53:39 +01:00
end