一起显示和排序多个查询

时间:2013-07-11 09:33:17

标签: ruby-on-rails ruby-on-rails-3 activerecord

我想显示组合来自多个查询的信息的数据。例如:

@projects = @company.projects
@assignments = @company.assignments
@tasks = @company.tasks

如何处理这三个查询并显示一个显示项目,作业和任务的大表,所有这些都按created_at排序?期望的结果如下所示:

7/11  Task created by company Xc for project Xp.
7/10  Project Xp created by User U.
7/09  Task created by company Yc for project Yp.
7/09  Assignment created by company Yc for project Yp.
7/08  Project Yp created by user U.

1 个答案:

答案 0 :(得分:2)

如果您想要执行更复杂的操作,例如仅获取最新的x条目或进行分页,则可以使用SQL UNION查询。

如果您知道数据很少,您可以在数组中收集结果并按created_at

排序
@events = @projects.to_a + @assignments.to_a + @tasks.to_a
@events.sort_by! { |e| e.created_at }