2012-03-16 25 views
-1

我很驚訝我的問題得到-1。它們並不簡單,它們很複雜。
我的line_items表有product_id cart_id order_id 只要客戶點擊產品,它就會被添加到購物車。 但我的公寓,汽車,旅遊包是不是產品。無論誰在想我可以連接到我的汽車產品,公寓告訴我。它們具有根本不同的屬性。當客戶點擊公寓並選擇2間臥室時,可以說我可以添加到line_items我的apartment_id或car_id或tour_id。請我不需要關於STI或多重繼承的理論。我需要完全的答案。感謝rails專家。不是簡單的購物車需要專家解答

+3

向下票很可能是因爲您沒有到_ask_一個問題,在這裏任何人都可以_understand_很好的回答了所需要的努力把什麼。看看其他問題,你會看到人們提供了很多細節,尤其是示例,並展示他們嘗試過的東西。問題越難,需要更多細節。如果你看看上面的問題,你會發現它假設我們理解你想做什麼的很多東西 - 有*沒有上下文*。寫一個獨立的問題(編輯這個!),你很可能會得到答案。 – 2012-03-16 12:52:15

回答

2

首先你應該格式化關於向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