i'm new rails , trying setup cookbook app practice. here have far:
db setup - 3 tables (simplified 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 problem. want retrieve list of ingredients recipe including qty , unit used can iterate through in view.
here tried (local variables shown, know have use instance variable use in view) :
recipe = recipe.first
recipe.ingredients
-> gives me ingredients recipe ingredients table, not include qty & unit recipe_ingredients table.
recipe.recipe_ingredients
-> gives me related records in recipe_ingredients table ingredient_id , not actual ingredient name.
how can retrieve recipe , ingredients including quantity , unit using least amount of queries? think 2 in case.
thank you,
leo
you looking includes
method. need :
recipe = recipe.includes(:ingredients, :recipeingredients).first
this return first recipe it's associated ingredients , recipe ingredients.