Rails 4 Accessing Join Table Attributes

后端 未结 2 489
一个人的身影
一个人的身影 2020-12-07 17:12

I have a has_many through join table setup for a recipe app where Ingredient and Meal connect through MealIngredient. Wit

2条回答
  •  甜味超标
    2020-12-07 17:21

    In this case, you should loop through the meal_ingredients association. You should eager load the ingredients association to reduce db queries.

    @meal.meal_ingredients.includes(:ingredient).each do |meal_ingredient|
      puts meal_ingredient.amount
      puts meal_ingredient.ingredient.name
    end
    

    UPDATE

    This update came after Rich Peck's answer but I think there's a simpler way to achieve what he did.

    @meal.ingredients.select('ingredients.*, meal_ingredients.amount').each do |ingredient|
      puts ingredient.amount
      puts ingredient.name
    end
    

提交回复
热议问题