0

I would like to display data that combines information from multiple queries. For example:

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

How can I take these three queries and display a big table that shows projects, assignments, and tasks, all sorted together by created_at? The desired result will look like this:

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 Answer 1

2

You can use a SQL UNION query for that if you want to do more complex stuff like getting the newest x entries only or for pagination.

If you know the data is very few, you can collect the results in an array and sort by created_at

@events = @projects.to_a + @assignments.to_a + @tasks.to_a
@events.sort_by! { |e| e.created_at }
Sign up to request clarification or add additional context in comments.

2 Comments

@events.sort_by!(&:created_at)
Yes, that shorthand is also good. But I believe the expanded form is easier to understand.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.