2017-09-30 2 views
-1

저는 Join 테이블 RecipeIngredients를 통해 has_many와 has_many로 연결된 Recipe 클래스와 Ingredient 클래스가 있습니다. 나는 몇몇 여과기를 창조하는 것을 시도하고 포함하는 성분의 수에 의하여 나의 조리법을 분류하는 것을 시도하고있다. 적절한 SQL을 알아낼 수 없으며, Arel을 사용하여 내 대답을 찾으려고합니다. 그러나이 시점에서이 질문에 대한 적절한 방법을 취할 것입니다. 반대로, 나는 또한 얼마나 많이 많은 조리법을 가지고 있는지 재료에 질문하려고 노력할 것입니다.Arel을 ROR 용으로 사용합니다. 클래스 관련 속성을 기반으로 쿼리하려고합니다.

누군가가 제공 할 수있는 도움을 미리 주셔서 감사합니다. 내 질문에 문제가있어 완전히 생각을 다했습니다. 오늘 밤. 감사.

답변

1

Arel을 사용하면 이러한 종류의 문제가 지나치게 복잡해질 수 있습니다. Arel 위의 레이어 인 ActiveRecord 자체는 매우 편안하게 해결할 수 있습니다.

나는 당신이 다음과 같은 SQL 문 생성해야합니다

성분의 숫자로 주문한 조리법을 얻기 위하여
class Recipe 
    has_many :recipe_ingredients 
    ... 
end 

class RecipeIngredient 
    has_one: :recipe 
    has_one: :ingredient 
    ... 
end 

class Ingredient 
    has_many :recipe_ingredients 
    ... 
end 

다음과 같은 모델이 가정

SELECT 
    recipes.id 
    ... 
    , recipes.[last_column_name] 
    # optionally 
    , COUNT(*) ingredients_count   
FROM 
    recipes 
OUTER JOIN 
    recipe_ingredients 
    ON 
    recipe_ingredients.recipe_id = recipe.id 
GROUP BY 
    ingredient_count DESC 

을하는 수 끝내야합니다

Recipe 
    .joins(:recipe_ingredients) 
    .group(Recipe.column_names) 
    .select(Recipe.column_names, 'COUNT(*) ingredients_count') 
    .order('ingredients_count DESC') # Or ASC 

반환되는 레시피 인스턴스는 재료. 그들은 또한 성분의 수를 돌려주는 추가 방법 ingredients_count을 가질 것입니다.

또한 레시피 클래스 내부의 스코프에 배치 할 수 있습니다.

Ingredient 
    .joins(:recipe_ingredients) 
    .group(Ingredient.column_names) 
    .select(Ingredient.column_names, 'COUNT(*) recipe_count') 
    .order('recipe_count DESC') # Or ASC 
: 반대의 경우
def self.ordered_by_ingredients_count 
    joins(:recipe_ingredients) 
    .group(column_names) 
    .select(column_names, 'COUNT(*) ingredients_count') 
    .order('ingredients_count DESC') # Or ASC 
end 

, 조리법의 수는 성분은 그냥 이름을 바꿀에서입니다
관련 문제