34 lines
978 B
Ruby
34 lines
978 B
Ruby
module JamRuby
|
|
class ShoppingCart < ActiveRecord::Base
|
|
|
|
attr_accessible :quantity, :cart_type, :product_info
|
|
|
|
belongs_to :user, :inverse_of => :shopping_carts, :class_name => "JamRuby::User", :foreign_key => "user_id"
|
|
|
|
validates :cart_id, presence: true
|
|
validates :cart_type, presence: true
|
|
validates :cart_class_name, presence: true
|
|
|
|
default_scope order('created_at DESC')
|
|
|
|
def product_info
|
|
product = self.cart_product
|
|
{name: product.name, price: product.price} unless product.nil?
|
|
end
|
|
|
|
def cart_product
|
|
self.cart_class_name.classify.constantize.find_by_id self.cart_id unless self.cart_class_name.blank?
|
|
end
|
|
|
|
def self.create user, product, quantity = 1
|
|
cart = ShoppingCart.new
|
|
cart.user = user
|
|
cart.cart_type = product.class::PRODUCT_TYPE
|
|
cart.cart_class_name = product.class.name
|
|
cart.cart_id = product.id
|
|
cart.quantity = quantity
|
|
cart.save
|
|
cart
|
|
end
|
|
end
|
|
end |