In Rails, how do I sort users by priority of tasks

Let's say I have two classes : User and Task. A task belongs to a user and has a priority (which is an integer between 1 and 3, or nil).

class User < ActiveRecord::Base
    has_many :tasks

class Task < ActiveRecord::Base
    belongs_to :user
    attr_accessible :priority # Integer between 1 and 3, or nil

I want to present a TOP 10 of users with the highest number of tasks and the highest priority (sort first by high priority then medium then low then unevaluated). I have thought of a different way but I can't find a clean way for handling this.

I first thought of using a complex SQL request in the controller's method for limiting performance:

User.joins(:tasks).count(:all, :group => ["tasks.user_id", "priority"])

However the result is not easy to be sorted and I finally have to use two loops for sorting and another one to render the Users. Furthermore, I think that this kind of method would be more logically in the model.

What do you think? What is the cleanest way to handle this?

Answers


If I understand correctly you want to sort the users who has the highest number of tasks with the highest priority right? So in a scenario:

  • User A has 3 tasks, 2 with priority 1 and 1 with 3
  • User B has 2 tasks, 2 with Priority 3
  • User C has 1 task with priority 2

And you'd expect the output to be: B, A, C?

I would just sum the task priorities and sort by that then:

User.joins(:tasks).group("users.id").order("SUM(tasks.priority) DESC").first(10)

The SQL may be a bit off as I am writing this off the top of my head, but you hopefully get the idea. The trick here is not so much the SQL but rather the weighting function you use to sort.


You can use following, just try this:

User.select("users.id, count(tasks.id) as task_count").
joins(:tasks).group("users.id").order("task_count desc").first(10)

This will work, i think. Though not tested.


Need Your Help

Start activity screen even if screen is locked in android

android android-activity broadcastreceiver screen-lock

How to start activity on device even if screen is locked.i tried as below but its not working.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.