Combine two queries into one and paginate together
I have two scoped queries that I need to paginate together. Individually, they look like this:
a = @person.company.tasks.open.paginate :page => params[:page], :order => (sort_column + " " + sort_direction)
b = @person.tasks.private.paginate :page => params[:page], :order => (sort_column + " " + sort_direction)
I would like to do something like the following:
@tasks = (a + b).paginate :page => params[:page], :order => (sort_column + " " + sort_direction)
What works
I do successfully get a merge when I do @tasks = (a + b)
and the results p开发者_如何学Caginate.
What doesn't
With the variables added together, the sorting doesn't work any more.
You can make one query, getting the tasks based on the id's returned by the 2 queries:
company_task_ids = @person.company.tasks.open.pluck(:id)
private_task_ids = @person.tasks.private.pluck(:id)
@tasks = Task.where(:id => (company_task_ids + private_task_ids)).paginate :page => params[:page], :order => (sort_column + " " + sort_direction)
This can be optimised a bit, but this should get you on your way
精彩评论