2014-12-13 2 views
1

이고 Recipe, IngredientRecipeIngredient입니다. 내 RecipeIngredienthas_many에서 조인 테이블의 추가 속성은

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

내가하지 않는 이상적인 방법으로 그것에 대해 갈 것 방법 등 amount, unit, type,

나는 이러한 추가 속성을 검색 할 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