2011-11-04 45 views
1

我有像這樣一個數據庫:如何正確創建記錄使用:通過?

class Store 
    hasMany :items 

class Item 
    belongsTo :store 

class Order 
    hasMany :items, :through => :order_items 

class OrderItem 
    belongsTo :order 

首先,這是正確的方式來建立這個數據庫?

最後,如何正確創建多個項目的記錄?

例如。

o = Order.new 
Order.items = [ [0,1], [3,4] ] # do you add them as an array? [order_id, item_id] ? 

我在正確的軌道上嗎?

謝謝!

回答

2

我想你應該從這裏開始:association basics。與許多其他框架不同,Rails具有很好的文檔。消化很容易,而且很有意義。另外選擇一本好的Intro to Rails 3書籍也是很好的建議。

要回答你的問題,上面的例子有幾個問題。對於初學者,它是has_manybelongs_to而不是hasManybelongsTo。就你的建模而言,儘管我會反對你當前的結構,但你仍然很接近。

我反對的原因是因爲一個訂單應該是一個記錄,在該給定實例下快照該項目。現在,如果你版本化你的項目,那麼你的模式工作得很好。如果您不這樣做,那麼您需要確保在訂單時記錄有關產品的相關信息,並且只有最少使用量的產品參考。

要回答這個問題的結構,與現在的設計方式,這裏是你將怎樣模型,可以:

class Store < ActiveRecord::Base 
    has_many :items 
end 

class Item < ActiveRecord::Base 
    belongs_to :store 
    has_many :order_items 
end 

class Order < ActiveRecord::Base 
    has_many :order_items 
    has_many :items, :through => :order_items 
end 

class OrderItem < ActiveRecord::Base 
    belongs_to :order 
    belongs_to :item 
end 

到您的下一個問題:

最後,如何你有多個項目正確創建記錄?

@order.items << item #where item is the instance of the item you want to add 
+0

謝謝。這是現貨。我不知道<<方法。順便說一句,你有機會知道如何傳遞一個自定義屬性?例如,我在我的OrderItem模型中有QUANTITY,所以理想情況下它就像「@ order.items << item,:quantity => 5」或類似的東西。我現在正在瀏覽文檔,但想到我也會問這裏。再次感謝。 – kidcapital

+0

你可能不想這樣做。將一個數量屬性添加到OrderItem中,並使其成爲一個完整的模型,而不僅僅是對Items的透視。 – Chance

相關問題