[英]Learning Rails -> Setup a Cookbook App
I'm new to Rails and trying to setup a cookbook app for practice. 我是Rails的新手,并尝试设置一个练习应用程序。 Here is what I have so far:
这是我到目前为止:
DB Setup - 3 tables (simplified for readability) 数据库设置 - 3个表(为便于阅读而简化)
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.ingredients
- >从配料表中给出了该配方的所有成分,但它不包括recipe_ingredients表中的数量和单位。
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. recipe.recipe_ingredients
- >给了我recipe_ingredients表中的所有相关记录,但我只得到ingredient_id而不是实际的成分名称。
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.
我认为在这种情况下它会是2。
Thank you, 谢谢,
Leo 狮子座
You are looking for the includes
method. 您正在寻找
includes
方法。 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. 这将返回第一个配方及其所有相关成分和配方成分。
You can add delegation to increase the functionality of your RecipeIngredient
instances. 您可以添加委派以增加
RecipeIngredient
实例的功能。
I would especially check out the prefix
section, otherwise you would only be able to delegate name
to one class. 我特别检查
prefix
部分,否则你只能将name
委托给一个类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.