添加项目到不同产品类型的购物车

问题描述:

嗨开发人员。我在添加商品到购物车时遇到问题。来自rails agile的书。如果我想添加到具有不同属性的产品(公寓,汽车)添加项目到不同产品类型的购物车

class Products 
    has_many :line_items 
    attributes :name, :price, :content 
end 

class LineItem 
    belongs_to :products 
    belongs_to :carts 
end 

class Cart 
    has_many :line_items 
end 

class Car 
    attributes :name, :car_type, :color 
end 

class Apartment 
    attributes :name, :size, :location 
end 

class Order 
    attr :buyer_details, :pay_type 
end 

客户将产品添加到购物车和e.x. 2间卧室出租,豪华轿车出租,并希望支付。如何添加到购物车。如果我将apartment_id和car_id放到lineitems中,它会污染吗?请我需要正确的做法,正确的做法。感谢所有。

查看多态关联如果您一定要将它全部保留在LineItems中。然后让LineItems成为产品,公寓和汽车的聚合物。但我认为你的设计在这里非常糟糕。购买和租赁是非常不同的。租用时,您将有一个持续时间,一个地址或注册,不得重复预订。回去处理你的ERD。更好的设计的

一个选项:

NB我已经改变了的LineItem是CartItem的清晰度。

class Products 
    has_many :cart_items 
    has_many :order_items 
    attributes :name, :price, :content 
end 


class Cart 
    has_many :line_items 
end 
class CartItem 
    belongs_to :products 
    belongs_to :carts 
end 
class CartRental 
    # :cart_rentable_type, :cart_rentable_id would be the fields for the polymorphic part 
    belongs_to :cart_rentable, :polymorphic => true 
    belongs_to :carts 
    attributes :from, :till 
end 

class Order 
    attr :buyer_details, :pay_type 
end 
class OrderItem 
    belongs_to :products 
    belongs_to :order 
end 
class Rental 
    belongs_to :rentable, :polymorphic => true 
    belongs_to :order 
    # :rentable_type, :rentable_id would be the fields for the polymorphic part 
    attributes :from, :till, :status 
end 


class Car 
    attributes :name, :car_type, :color 
    has_many :cart_rentals, :as => :cart_rentable 
    has_many :rentals, :as => :rentable 
end 
class Apartment 
    attributes :name, :size, :location 
    has_many :cart_rentals, :as => :cart_rentable 
    has_many :rentals, :as => :rentable 
end 
+0

这是我的问题。如果这是不好的设计,那么正确的做法是什么?上面的 – 2012-03-17 00:28:36

+0

答案更新了一个应该为你工作的例子 – TomDunning 2012-03-17 09:19:53