0

Je voulais construire un livre de cuisine de base. Avec une relation Ingrtients Relation habtm.Ajouter une quantité à une recette habtm Ingrédients Relation

Ma première tentative était comme ceci.

class Recipe < ActiveRecord::Base 
    # title, description 
    has_many :recipe_ingredients 
end 

class Ingredient < ActiveRecord::Base 
    # name, unit 
    has_many :recipe_ingredients 
    has_many :recipes, :through => :recipe_ingredients 
end 

class RecipeIngredient < ActiveRecord::Base 
    belongs_to :recipe 
    belongs_to :ingredient 
    attr_accessible :amount 
end 

et a créé la relation en main

RecipeIngredient.create(:recipe_id => 1, :ingredient_id => 2, :amount => 100) 

recipe.recipe_ingredients.amout 
recipe.recipe_ingredients.ingredient.unit 
recipe.recipe_ingredients.ingredient.name 

Cela se sent laid. Mais je ne connais aucune autre solution.

Répondre

3

Cela me semble bien, comme un schéma/approche. Je pense que cela pourrait être laide parce que votre choix de nom de classe vous amène à taper "recipe.recipe_ingredients.ingredient" beaucoup. Pour moi, un «ingrédient» est la nourriture/liquide/tout comme il est utilisé dans la recette, de sorte que la table de jointure devrait être appelée «ingrédients». Chaque ingrédient a une quantité et des liens vers un «produit» ou un «article» ou quelque chose de similaire.

Je le renommer ainsi:

Recipe 
    has_many :ingredients 
    has_many :items, :through => :ingredients 

Ingredient 
    #fields - recipe_id, item_id, quantity(string) 
    belongs_to :recipe 
    belongs_to :item 

Item 
    has_many :ingredients 
    has_many :recipes, :through => :ingredients 

maintenant sur votre page de vue, vous pouvez dire

<h2><%= recipe.name %></h2> 
<dl> 
    <% @recipe.ingredients.each do |ingredient| %> 
    <dt><%= ingredient.item.name %></dt> 
    <dd><%= ingredient.quantity %></dd> 
    <% end %> 
</dl> 
+1

Yay frappe recipes.recipes ... est mauvais. Merci – Henning

0

Je suppose que vous manque has_many: grâce au modèle receipe

classe Receipe < ActiveRecord :: Base

has_many: receipe_ingre ingré-

has_many: ingrédients,: à travers =>: receipe_ingredients

fin

classe Ingrédient < ActiveRecord :: Base

has_many: receipe_ingredients

has_many: receipes,: à travers => : receipe_ingredients

fin

classe ReceipeIngredient < ActiveRecord :: Base

belongs_to: receipe

belongs_to: ingrédient

fin

Questions connexes