Learning Rails & # 8594; Setting up a cookbook app

I am new to Rails and am trying to set up a cookbook app for practice. Here's what I have so far:

Database setup - 3 tables (easy to read)

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 get a list of ingredients for a recipe including the qty and the device used so I can scroll through it in my opinion.

Here's what I tried (local variables are shown, I know I need to use an instance variable to use):

recipe = Recipe.first

      

recipe.ingredients

-> gives me all the ingredients for this recipe from the ingredients table, but it does not include the quantity and block from the recipe_ingredients table.

recipe.recipe_ingredients

-> gives me all the associated entries in the recipe_ingredients table, but I only get the componentient_id and not the actual name of the ingredient.

How can I get a recipe and all its ingredients, including quantity and unit, using the least amount of requests? I think there will be 2 in this case.

Thank,

Leo

+3


source to share


2 answers


You are looking for a method includes

. You need something like this:

recipe = Recipe.includes(:ingredients, :recipeingredients).first

      



this will return the first recipe with all its ingredients and recipe ingredients.

+4


source


You can add delegation to increase the functionality of your instances RecipeIngredient

.



I would especially look at the section prefix

, otherwise you might only be delegating to name

one class.

-1


source







All Articles