I'm new to Rails and trying to setup a cookbook app for practice. Here is what I have so far:
DB Setup - 3 tables (simplified for readability)
recipes (id, name, description)
recipe_ingredients (id, recipe_id, ingredient_id, qty, unit)
ingredients(id, name)
Models
class Recipe < ActiveRecord::Base
has_many :recipe_ingredients, dependent: :destroy
has_many :ingredients, through: :recipe_ingredients
end
class RecipeIngredient < ActiveRecord::Base
belongs_to :recipe
belongs_to :ingredient
end
class Ingredient < ActiveRecord::Base
has_many :recipe_ingredients
has_many :recipes, through: :recipe_ingredients
end
Here is my problem. I want to retrieve a list of ingredients for a recipe including qty and the unit used so I can iterate through it in my view.
Here is what I tried (local variables shown, I know I have to use instance variable to use in view) :
recipe = Recipe.first
recipe.ingredients -> gives me all ingredients for that recipe from the ingredients table, but it does not include the qty & unit from recipe_ingredients table.
recipe.recipe_ingredients -> gives me all related records in the recipe_ingredients table but I only get ingredient_id and not the actual ingredient name.
How can I retrieve the recipe and all its ingredients including quantity and unit using the least amount of queries? I think it would be 2 in this case.
Thank you,
Leo
You are looking for the includes method. You need something like this :
recipe = Recipe.includes(:ingredients, :recipeingredients).first
this will return the first recipe with all it's associated ingredients and recipe ingredients.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With