I want to display a list with tags plus the number of elements (in my example "Tasks") for each tag.
For this purpose I created the following method in my Tag model:
def self.find_with_count
find_by_sql 'SELECT
Tag.name,
COUNT(Tag.name) AS taskcount
FROM
tags AS Tag
INNER JOIN tags_tasks tt ON tt.tag_id = Tag.id
INNER JOIN tasks t ON tt.task_id = t.id
WHERE
t.finished = 0
AND t.deleted = 0
GROUP BY
Tag.name
ORDER BY
Tag.name'
end
The method returns the correct tag names, but for some reason the taskcounts are not in the result. The result looks like
[#<Tag name: "hello">, #<Tag name: "world">]
As this approach doesn't seem to work, I'm wondering what the Rails-way is to accomplish such a task. Thanks!