I have a rails app with "recipes" model. Recipe can be liked ("like" model) by a user. What I'd like to achieve (eventually) is to sort the list of the recipes on the recipes-index page by the number of likes.
I've seen numerous threads but the two that guided me the most were:
Rails 3 ActiveRecord: order and group by association count
Rails order by results count of has_many association
I've got so far that I have an SQL-query that produces list of the recipes with the count of their likes:
SELECT recipes.name, COUNT(likes.id)
FROM recipes
LEFT JOIN likes on recipes.id = likes.recipe_id
GROUP BY recipes.name
ORDER BY COUNT(likes.id) DESC;
However, when "translating" it to something ActiveRecord can understand, I'm running into troubles.
I've concluded that using Recipe.joins(:likes) or Recipe.left_joins(:likes) passes all columns specified in "recipes", which leads to the following error:
"Column "recipes.id" must appear in the GROUP BY clause or be used in an aggregate function...".
Now, as I need to pass recipes.name and COUNT(likes.id) only, I used select:
Recipe.select("recipes.name, COUNT(likes.id)").joins(:likes).group("recipes.name").order("COUNT(likes.id) DESC")
And that's where I'm stranded as it produces this:
ActiveRecord::Relation [Recipe id: nil, name: "Scrambled eggz", Recipe id: nil, name: "Soup", Recipe id: nil, name: "Nutella pancakes"]