2014-12-13 30 views
1

中的連接表的額外屬性我有一個Recipe,IngredientRecipeIngredient從has_many到

class Recipe 
    has_many :recipe_ingredients 
    has_many :ingredients, through: :recipe_ingredients 
end 

RecipeIngredient有一個像amountunittype

如果我從recipe.ingredients想找回這些額外的屬性附加屬性,我將如何去在那個非常不的方式引入N + 1查詢或其他任何會降低性能的問題?

回答

0
ingredients = recipe.ingredients.all 
recipe_ingredients = recipe.recipe_ingredients.all 

# only two queries. no queries beyond this point 

ingredients.each do |ingredient| 
    recipe_ingredient = recipe_ingredients.find {|it| it.ingredient_id == ingredient.id } 
    recipe_ingredient.amount # etc 
end 

也許這樣的事情?

1

未經測試,但你可以打電話給我

你的問題有點含糊,但我認爲這是你在找什麼:

recipe = Recipe.includes(:ingredients).find(1) 

當然你也可以更換find(1)all或任何你想使用的方法。

然後,當您從配方的其中一個配料中選擇一個屬性時,它將不會生成另一個查詢,因爲它已經提取了它。

參考:

http://apidock.com/rails/ActiveRecord/QueryMethods/includes