アイテムごとに 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 があるとすると、次のようになります。
@recipe.subrecipes # find all subrecipes required to make this recipe
@recipe.recipes # find all recipes using this as a subrecipe
また、他のコンポーネントで構成されていないものに使用できる RawComponent クラスも追加されました。ただし、すべての RawComponent をサブレシピなしで Recipe にする場合は、必要ありません。これは、状況をモデル化する有効な方法でもあります。
重要なポイントは、関連付けモデル (RecipeComponents) が階層の上位にある :recipe と、階層の下位にあるがレシピと同じクラス タイプの :subrecipe に属していることです。