Sum of ingredients in recipes model to create shoppinglist

走远了吗. 提交于 2020-01-06 14:45:25

问题


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. Ingredienzations contains the amount, measurement type (grams, teaspoons etc.) and recipe_id.


回答1:


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. It becomes much more tricky if you have units on you amounts. But this query can be rewritten to make that work as well.



来源:https://stackoverflow.com/questions/26829121/sum-of-ingredients-in-recipes-model-to-create-shoppinglist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!