简体   繁体   English

配方模型中成分的总和以创建购物清单

[英]Sum of ingredients in recipes model to create 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

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. Shoppinglistingredienzations具有一个整数“人”以告诉应计算要服务的人数,而食谱具有人变量以显示该食谱适用于多少人。 Ingredienzations contains the amount, measurement type (grams, teaspoons etc.) and recipe_id. 检验包含量,计量类型(克,茶匙等)和配方ID。

You could do this: 您可以这样做:

Shoppinglist.where(id: list_id).joins({recipes: : ingredients}).group('ingredients.name').sum('ingredients.amount')

assuming your Ingredient model has the attributes amount and name. 假设您的Ingredient模型具有属性数量和名称。 It becomes much more tricky if you have units on you amounts. 如果数量上有单位,它将变得更加棘手。 But this query can be rewritten to make that work as well. 但是此查询也可以重写以使其正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM