问题
I tried
@posts = Post.page(params[:page]).per_page(10)
and
@posts = Post.paginate(:page => 1, :per_page => 10)
but neither method works
undefined method `page' for Post:Class
undefined method `paginate' for Post:Class
How do you do pagination with mongoid?
回答1:
You should use Kaminari https://github.com/amatsuda/kaminari
回答2:
This works fine for me:
@posts = Post.paginate(:page => 1, :limit => 10).desc(:_id)
desc(:_id)
is added so that latest posts could be listed first.
回答3:
Still using will_paginate is also okay.
This thread has same issue: undefined method `paginate' for Array on Rails 3 with mongoid
The main point to fix the error is to add this line before the controller call paginate library:
require 'will_paginate/array'
It should be added to default config file if you use mongoid for the whole project.
Hope the explanation helpful.
Reference from origin gem source: https://github.com/mislav/will_paginate/wiki/Backwards-incompatibility at "WillPaginate::Collection" section.
P/S: this is just a work around if your query is not very large. If you want better performance, let's try mongoid-pagination gem, custom will_pagination gem or another pagination gem which supported Mongoid like kaminari.
回答4:
A bit late, but for anyone else looking, I found 'will_paginate_mongoid'
https://github.com/lucasas/will_paginate_mongoid
Really straight forward and lets you simply do
collection.skip(20).limit(10)
回答5:
Use the following gem.
Very helpful.
https://github.com/lucasas/will_paginate_mongoid
回答6:
silly thing, but it worked for me in sinatra after i added require 'mongoid-pagination' to app.rb
回答7:
Posting several years later, in case someone else faces the same challenge.
kaminari-mongoid
was released in 2016, and is currently maintained.
https://github.com/kaminari/kaminari-mongoid
All the goodness of Kaminiari for Mongoid, including appropriate handling of Mongoid::Criteria
results, which was possibly the cause of the OP's error.
回答8:
To update a bit the answers, now exists the Pagy gem, also much more performant (cpu/mem) than will_paginate and kaminari. This is a migration guide
来源:https://stackoverflow.com/questions/8549256/mongoid-pagination