我想显示组合来自多个查询的信息的数据。例如:
@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.
答案 0 :(得分:2)
如果您想要执行更复杂的操作,例如仅获取最新的x条目或进行分页,则可以使用SQL UNION
查询。
如果您知道数据很少,您可以在数组中收集结果并按created_at
@events = @projects.to_a + @assignments.to_a + @tasks.to_a
@events.sort_by! { |e| e.created_at }