How to order grouped data in Rails 7?

202 Views Asked by At

I am trying to get data that is grouped by :user_id for bar charts.

@completed_tasks = Task.where(completed: true).group(:user_id)

enter image description here I want to organize it in descending order.

Howe can I do it? In addition to it, is there a chance to rename the y-axis values? Thanks in advance

I have tried to work with the following with different variables instead of ... , but it did not work:

@completed_tasks = Task.where(completed: true).group(:user_id).order("count(...) DESC")

UPDATE: My query had been ordered. The problem is that Chartkick orders values for axis. Is there a chance to make axis unordered?

Chart code:

<%= bar_chart @completed_tasks.count%>
1

There are 1 best solutions below

4
Harry Train On

I managed to perform this task by raw sql, but honestly, I tried serveral ways by using Rails Active record ORM. Hope my code could help a little bit:

sql = "Select count(id) as count_all, user_id from Tasks group_by user_id count_all desc"
records_array = ActiveRecord::Base.connection.execute(sql) 
records_array.values

You will receive an array like: [[10, 2], [9,3], ...] in which 2,3 will be user_id, and 10,9 will be the number of records having correponding user_id.