不是简单的购物车需要专家解答
问题描述:
我很惊讶我的问题得到-1。它们并不简单,它们很复杂。
我的line_items表有product_id cart_id order_id 只要客户点击产品,它就会被添加到购物车。 但我的公寓,汽车,旅游包是不是产品。无论谁在想我可以连接到我的汽车产品,公寓告诉我。它们具有根本不同的属性。当客户点击公寓并选择2间卧室时,可以说我可以添加到line_items我的apartment_id或car_id或tour_id。请我不需要关于STI或多重继承的理论。我需要完全的答案。感谢rails专家。不是简单的购物车需要专家解答
答
首先你应该格式化关于向SO
指引你的问题,那是也许是因为你得到downvotes ...
无论如何,我认为你正在寻找polymorphic associations。
假设Product
,就是要在你的店铺和LineItem
产品一问世代表了一个订单一个产品:
class LineItem < ActiveRecord::Base
has_one :product # ONE LineItem references ONE product in the shop
belongs_to :cart # respectively belongs_to :order
end
class Cart < ActiveRecord::Base
has_many :line_items # ONE Cart HAS MANY LineItems
end
class Product < ActiveRecord::Base
belongs_to :buyable, :polymorphic => true
# here you would have general attributes representing a product, e.g. 'name'
end
class Car < ActiveRecord::Base
has_one :product, :as => :buyable
# here you would have specific attributes in addition to the general attributes in
# product, e.g. 'brand'
end
class Apartment < ActiveRecord::Base
has_one :product, :as => :buyable
# here you would have specific attributes in addition to the general attributes in
# product, e.g. 'address'
end
,使这项工作你products
表必须有两列
- buyable_type(string)
- buyable_id(整数)
因此,在你的代码,你可以检查你的产品是做
@product = Product.find(params[:id])
if @product.buyable.is_a? Car
puts @product.buyable.brand
elsif @product.buyable.is_a? Apartment
puts @product.buyable.address
end
+0
感谢Vapire的正确方向 – 2012-03-16 13:16:08
向下票很可能是因为您没有到_ask_一个问题,在这里任何人都可以_understand_很好的回答了所需要的努力把什么。看看其他问题,你会看到人们提供了很多细节,尤其是示例,并展示他们尝试过的东西。问题越难,需要更多细节。如果你看看上面的问题,你会发现它假设我们理解你想做什么的很多东西 - 有*没有上下文*。写一个独立的问题(编辑这个!),你很可能会得到答案。 – 2012-03-16 12:52:15