-2

次の関連付けを持つアイテムの1つのテーブルを作成するにはどうすればよいですか。

私の最終目標は、多くのコンポーネントとサブレシピを含むレシピを作成できるようにすることです(これらを1つのドロップダウンに結合したい)

Component

  belongs_to sub_recipe

End

Sub_recipe

  has_many components

  belongs_to recipe

End

Recipe 

  has_many subrecipes

  has_many components

End
4

1 に答える 1

1

アイテムごとに 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 に属していることです。

于 2012-08-17T05:48:30.747 に答える