2012-08-17 19 views
-2

我會怎麼做的項目之一表具有以下關聯:Rails的模型配方和子配方協會

我的最終目標是要能夠創建具有許多組件和子食譜食譜(我要合併成一個下拉)

Component 

    belongs_to sub_recipe 

End 

Sub_recipe 

    has_many components 

    belongs_to recipe 

End 

Recipe 

    has_many subrecipes 

    has_many components 

End 
+0

這個問題沒有任何意義。你能解釋你想做什麼嗎? – 2012-08-17 01:25:05

回答

1

你想爲每個項目一個表,併爲協會

#class RawComponent < ActiveRecord::Base 
# has_and_belongs_to_many :recipes 
#end 

class Recipe < ActiveRecord::Base 
    has_many :recipe_components 
    has_many :subrecipes, :through => :recipe_components 
    has_many :recipes, :through => :recipe_components 
# has_and_belongs_to_many :raw_components 
end 

class RecipeComponents < ActiveRecord::Base 
    belongs_to :recipe 
    belongs_to :subrecipe, :class_name => :Recipe 
end 

假設你有一個@recipe一個表,你可以TH en go:

@recipe.subrecipes # find all subrecipes required to make this recipe 
@recipe.recipes # find all recipes using this as a subrecipe 

還添加了可能的RawComponent類,您可以將它用於非由其他組件組成的事物。但是,如果您將每個RawComponent製作成沒有任何子配方的配方,則不需要它,這也是模擬情況的有效方法。

關鍵問題是,關聯模型(RecipeComponents)屬於層次結構中較高的配方,以及層次結構中較低但與配方具有相同類類型的子配方。

+0

輝煌。你是最好的ronalchn! – FellyTone84 2012-08-17 07:02:51

+0

ronalchn,當你說「你想要一個單一的表爲每個項目」你的意思是我只需要一個食譜表?如果是這樣,我需要添加哪些列來正確表示這些關聯? – FellyTone84 2012-08-17 15:24:34

+0

我的意思是你需要兩張桌子。一個用於存儲項目,另一個用於存儲關聯。 – ronalchn 2012-08-17 23:07:33