简体   繁体   English

如何使用 Rails 中的 Pagy gem 对多个模型进行分页?

[英]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.我使用SearchkickPagy宝石进行分页我的搜索结果和它的伟大工程,如果我只是在搜索和分页的一个模型,但我想不通的时候,我需要多种模式如何与Pagy做到这一点成一组 Searchkick 搜索结果。

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.我尝试使用 Pagy 的“ array extra ”将所有单独的 Searchkick 模型查询组合到一个数组中,然后循环查看视图中的结果,但这并没有返回任何搜索结果。

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:以下内容用作跨多个模型的组合 Searchkick 查询,但不分页:

@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: Pagy 的“ Array Extra ”的文档警告:

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.使用 Pagy 对来自多个模型的 Searchkick 结果进行分页似乎是可能的。 If you're not supposed to use a Pagy array to do this, then how are you supposed to do this?如果您不应该使用 Pagy 数组来执行此操作,那么您应该如何执行此操作?

You can put this in the pagy initializer:你可以把它放在 pagy 初始值设定项中:

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.它没有记录,因此您可能应该为丢失的文档创建一个文档问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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