我有一个shoppinglist模型,其中有许多食谱,它也有许多成分。
I Have a shoppinglist model which has many recipes, which again has many ingredients.
class Shoppinglist < ActiveRecord::Base has_many :shoppinglistrecipezations has_many :recipes, :through => :shoppinglistrecipezations end class Recipe < ActiveRecord::Base has_many :shoppinglistrecipezations has_many :shoppinglists, :through => :shoppinglistrecipezations has_many :ingredients, :through => :ingredienzations has_many :ingredienzations end class Ingredient < ActiveRecord::Base has_many :recipes, :through => :ingredienzations has_many :ingredienzations end当我添加多个配方的购物模式(其中一些有相同的成分),我想打印在shoppinglist和配料适量所有ingrediens的列表。 Shoppinglistingredienzations有一个整数人,告诉有多少人曾应计算和配方有一个人的变量来显示有多少人的食谱是。 Ingredienzations含有量,测量类型(克,茶匙等)和recipe_id
When I add several recipes to the shopping model (some of them have the same ingredients) I want to print a list of all the ingrediens in the shoppinglist and the right amount of ingredients. Shoppinglistingredienzations has an integer "Persons" to tell how many persons served should be calculated for and Recipe has a persons variable to show how many persons the recipe is for. Ingredienzations contains the amount, measurement type (grams, teaspoons etc.) and recipe_id.
推荐答案你可以这样做:
Shoppinglist.where(id: list_id).joins({recipes: : ingredients}).group('ingredients.name').sum('ingredients.amount')
假设你的成分模型具有的属性数量和名称。它变得更加棘手,如果你有单位对你金额。但是,此查询可以改写,使这项工作也是如此。
assuming your Ingredient model has the attributes amount and name. It becomes much more tricky if you have units on you amounts. But this query can be rewritten to make that work as well.
更多推荐
成分的配方模型和为创建shoppinglist
发布评论