问题
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