我会考虑使用 Arel 来解决这种过于复杂的问题。 ActiveRecord 本身,它是 Arel 之上的一层,可以很轻松地解决这个问题。
我假设您有以下型号
class Recipe
has_many :recipe_ingredients
...
end
class RecipeIngredient
has_one: :recipe
has_one: :ingredient
...
end
class Ingredient
has_many :recipe_ingredients
...
end
为了获得按成分数量排序的食谱,您必须生成以下 SQL 语句:
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
返回的 Recipe 实例将按成分数量排序。他们还将有一个额外的方法 ingredients_count 返回成分的数量。
这也可以放在 Recipe 类的范围内。
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
反之,一种成分的配方数量,只需交换一些名称:
Ingredient
.joins(:recipe_ingredients)
.group(Ingredient.column_names)
.select(Ingredient.column_names, 'COUNT(*) recipe_count')
.order('recipe_count DESC') # Or ASC