When using Rails and Kaminari, is it possible to limit the maximum number of results to be returned for a given query?
@things = Thing.page(params[:page]).per(10)
Assuming we have 500k+ Thing
records in the database, how can I ensure that Kaminari's paginate
method will never return more than 10,000 rows to paginate?
Kaminari有一个max_per_page
选项可能会有所帮助,但可以通过此处也提供的limit scope方法来工作。
So, I figured out a way to do that using an initializer for Kaminari in config/initializers/kaminari_config.rb
:
Kaminari.configure do |config|
config.default_per_page = 10
config.max_per_page = 100
config.max_pages = 100
end
In the above case, 100 * 100 = 10,000 maximum total results
More info here
So you're interested in just the top 10k rows? This should do it, but I would consider adding some sorting criteria in there (before the call to limit
) so that your chosen 10000 rows make sense.
Thing.limit(10000).page(params[:page]).per(10)
max_per_page
actually sets settings globally. To have individual resource based settings, Kaminari supports Array
type objects as well. So, something like below works perfect:
limited_newsfeeds = Newsfeed.order(:created_at).limit(20)
@newfeeds = Kaminari.paginate_array(limited_newsfeed).page(params[:page]).per(3)
You may easily use this @newsfeed
object same like normal collection in kaminari views, like
<%= paginate @newsfeeds, remote: true %>
TIP : Using limit()
method directly before/after page()
doesn't serve the purpose. It either overwrites kaminari's limit (when used after page()
method), or gets replaced-by kaminari's limit (when used before page()
method)
Source: https://github.com/kaminari/kaminari#paginating-a-generic-array-object
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.