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
, 조리법의 수는 성분은 그냥 이름을 바꿀에서입니다