简体   繁体   中英

How to paginate multiple models with the Pagy gem in Rails?

I'm using Searchkick with the Pagy gem to paginate my search results and it works great if I'm only searching and paginating on one model, but I can't figure out how to do this with Pagy when I need to combine multiple models into one set of Searchkick search results.

I tried using Pagy's " array extra " to combine all the the individual Searchkick model queries into an array and then loop through the results in the view, but that did not return any search results.

Here's the controller code that works for a single model:

query = params[:q].presence || "*"
results = BlogPost.pagy_search(query, suggest: true, per_page: 20)
@pagy, @results = pagy_searchkick(results, items: 10)

And in the view:

<%= pagy_nav(@pagy).html_safe %>

The following works as a combined Searchkick query across multiple models, but it's not paginated:

@search_results = Searchkick.search(query, models: [PressRelease, BlogPost, User])

How am I supposed to paginate across multiple models, then? The docs for Pagy's " Array Extra " warns:

if the data in the array comes from some DB or other persisted storage (ie not some in-memory storage), then you should definitely review your code

That's exactly what I'm trying to do. Using Pagy to paginate Searchkick results from multiple models seems like something that should be possible. If you're not supposed to use a Pagy array to do this, then how are you supposed to do this?

You can put this in the pagy initializer:

Searchkick.extend Pagy::Searchkick

Then you can use it as usual:

results = Searchkick.pagy_search(query, models: [PressRelease, BlogPost, User])
@pagy, @results = pagy_searchkick(results, items: 10)

It is not documented, so you should probably create a Documentation Issue for the missing documentation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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