ruby on rails - Ingredient has many sub-ingredients modelling -
i've got recipe
model, , ingredient
model. right recipe has_and_belongs_to_many :ingredients
, ingredient has_and_belongs_to_many :recipes
.
because ingredient conceivably made of other ingredients, i'm trying self-join on model, so:
has_many :components, class_name: 'ingredient', foreign_key: 'parent_id' belongs_to :parent, class_name: 'ingredient'
now, works, each ingredient can have 1 parent, e.g., mayonnaise in "crab cakes" ingredient part of recipe, can't ingredient in "spicy mayo" ingredient of other recipe simultaneously.
what i'm trying interface this:
r = recipe.create(name: "jumbo lump crab cakes") r.ingredients << ingredient.create(name: "crab cakes") r.ingredients[0].ingredients # => [] r.ingredients[0].ingredients.create(name: "mayonnaise") r.ingredients[0].ingredients # => [#<ingredient id: 2, name: "mayonnaise">] r.ingredients[0].ingredients[0].ingredients.create(name: "eggs") r.ingredients[0].ingredients[0].ingredients # => [#<ingredient id: 3, name: "eggs">] ingredient.last # => #<ingredient id: 3, name: "eggs"> ingredient.last.parent # => #<ingredient id: 2, name: "mayonnaise"> ingredient.last.parent.parent # => #<ingredient id: 1, name: "crab cakes"> # bonus points if child ingredient can "walk up" heritage tree recipe: ingredient.last.recipe # => #<recipe id: 1>
obviously need association table store ingredient/sub-ingredient relationships, that's far i've figured out. i've tried various feats of source
, through
wizardry no luck.
i messed around polymorphic association, has parent , it's either of type ingredient or of type recipe, couldn't work out interface wanted.
think got figured out. ended using modified version of this post.
create_table :ingredients |t| # :hunts t.references :parent # :predator t.references :child # :prey end add_index :ingredients, :parent_id # :hunts, :predator_id add_index :ingredients, :child_id # :hunts, :prey_id create_table :components |t| # :animals t.string :name end class component < activerecord::base # animal has_many :parentage, foreign_key: 'parent_id', class_name: 'ingredient', dependent: :destroy has_many :children, through: :parentage has_many :progeny, foreign_key: 'child_id', class_name: 'ingredient', dependent: :destroy has_many :parents, through: :progeny end class ingredient < activerecord::base # hunt belongs_to :parent, class_name: 'component' belongs_to :child, class_name: 'component' end
fairly happy parentage/progeny naming.
Comments
Post a Comment