I have a Recipe
, Ingredient
, and RecipeIngredient
.
class Recipe
has_many :recipe_ingredients
has_many :ingredients, through: :recipe_ingredients
end
My RecipeIngredient
has additional attributes like amount
, unit
, type
, etc.
If I wanted from a recipe.ingredients
to retrieve these extra attributes, how would I go about that in a way that ideally does not introduce N+1 queries or anything else that degrades performance?
Untested but you can get back to me
Your question is a little vague but I think this is what you are looking for:
recipe = Recipe.includes(:ingredients).find(1)
Of course you can replace the find(1)
with all
or whatever method you want to use.
Then when you select an attribute from one of the ingredients of a recipe, it won't generate another query since it will have already fetched it.
Reference:
ingredients = recipe.ingredients.all
recipe_ingredients = recipe.recipe_ingredients.all
# only two queries. no queries beyond this point
ingredients.each do |ingredient|
recipe_ingredient = recipe_ingredients.find {|it| it.ingredient_id == ingredient.id }
recipe_ingredient.amount # etc
end
Something like that perhaps?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.