简体   繁体   English

在Rails中,如何按任务优先级对用户进行排序

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

Let's say I have two classes : User and Task. 假设我有两个类:User和Task。 A task belongs to a user and has a priority (which is an integer between 1 and 3, or nil). 任务属于用户并具有优先级(1到3之间的整数,或者为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). 我想呈现具有最高任务数和最高优先级的前10名用户(首先按高优先级排序然后按中等然后低则再评估未评估)。 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: 我首先想到在控制器的方法中使用复杂的SQL请求来限制性能:

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? 处理这个问题的最简洁方法是什么?

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. 虽然没有经过测试

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 用户A有3个任务,2个优先级为1,1个为3个
  • User B has 2 tasks, 2 with Priority 3 用户B有2个任务,2个优先级为3
  • User C has 1 task with priority 2 用户C有1个优先级为2的任务

And you'd expect the output to be: B, A, C? 你期望输出为: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. SQL可能有点偏离,因为我正在写这篇文章,但你希望得到这个想法。 The trick here is not so much the SQL but rather the weighting function you use to sort. 这里的诀窍不是SQL,而是你用来排序的加权函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM