简体   繁体   English

Rails中的“复杂”分组和索引编制?

[英]“Complex” grouping and indexing in rails?

I have a problem to which I can't seem to find a simple solution. 我有一个似乎无法找到简单解决方案的问题。

I want to achieve the following: 我要实现以下目标:
* i have a list of tasks, each with an owner and a due date *我有一个任务列表,每个任务都有一个所有者和到期日
* i want to display a list of all tasks grouped by owner *我想显示按所有者分组的所有任务的列表
* i want to sort the owners based on the due dates: eg The owner with the lowest due date first, followed by the owner with the second lowest, etc *我想根据到期日对所有者进行排序:例如,到期日最低的所有者排在第一,其次是最低的所有者,依此类推
* I want to be able to paginate the results, preferable with will_paginate *我希望能够对结果进行分页,最好使用will_paginate

To ilustrate, this would be a result i am looking for: 为了说明,这是我要寻找的结果:

Harry 掠夺
- task 1, due date 1 -任务1,截止日期1
- task 3, due date 4 -任务3,到期日4
Ben
- task 2, due date 2 -任务2,截止日期2
Carol 颂歌
- task 4, due date 3 -任务4,截止日期3

So far, I can query for all owners with tasks, sort them on a virtual attribute with their "earliest due date" and then display them and their tasks in a view. 到目前为止,我可以查询与任务的所有业主,在与他们的“最早到期日”的虚拟属性进行排序,然后在视图中显示他们他们的任务。

There are multiple problems with this approach, imo: imo这种方法存在多个问题:
* i run multiple queries from the view (owner.tasks.each etc). *我从视图中运行多个查询(owner.tasks.each等)。 I always learned that running queries from the view is bad 我总是了解到从视图中运行查询是不好的
* i'm doing the sorting by loading all records in memory (virtual attribute), which could get problematic with large records set. *我正在通过将所有记录加载到内存(虚拟属性)中来进行排序,这对于大型记录集可能会造成问题。 * I have no idea how i can get pagination in on this, that will be sensitive to the amount of tasks displayed *我不知道该如何进行分页,这将对显示的任务数量敏感

I can't seem to crack this nut, so any help or hints would be greatly appreciated! 我似乎无法破解,所以任何帮助或提示将不胜感激!
Erwin 欧文

Try this query, you have not provided sample data (ideally using SQL) so that we could play ourselves: 试试这个查询,您没有提供示例数据(理想情况下使用SQL),因此我们可以发挥自己的作用:

SELECT
u.id as owner_id, u.name as owner_name, t.id, t.due_date
FROM users u
INNER JOIN tasks m ON u.id = m.owner_id
INNER JOIN tasks t ON u.id = t.owner_id
GROUP BY u.id, u.name, t.id, t.due_date
ORDER BY MIN(m.due_date), t.due_date

You should get all the data you need in the proper order, and you can paginate simply by applying LIMIT to it (or converting it to AR and submitting it to will_paginate). 您应该以正确的顺序获取所需的所有数据,并且只需对它应用LIMIT (或将其转换为AR并将其提交给will_paginate)即可进行分页。

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

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