Using will_paginate with Sequel and Mongoid
will_paginate
provides integrations for popular alternatives to ActiveRecord, including the Sequel ORM and the Mongoid ODM for MongoDB.
Sequel
The Sequel ORM has its own robust pagination support through the sequel/extensions/pagination
extension. The will_paginate
gem provides a compatibility layer that makes Sequel's paginated datasets work seamlessly with the will_paginate
view helpers.
Setup
First, ensure you have Sequel's pagination extension enabled and then require the will_paginate
integration file.
require 'sequel'
require 'sequel/extensions/pagination'
require 'will_paginate/sequel'
# Connect to your database
DB = Sequel.sqlite # for example
# Enable pagination on your dataset
class Car < Sequel::Model
self.dataset = dataset.extension(:pagination)
end
Usage
You can now use Sequel's native paginate
method. The resulting dataset will have methods like total_pages
, per_page
, total_entries
, and current_page
, making it compatible with will_paginate
view helpers.
# Get the first page with 2 cars per page
@cars = Car.dataset.paginate(1, 2)
@cars.current_page # => 1
@cars.page_size # => 2 (aliased to per_page)
@cars.page_count # => 2 (aliased to total_pages)
# This works with filters and orders as well
@cars = Car.order(:name).filter(name: 'Shelby').paginate(1, 10)
Mongoid
For Mongoid, will_paginate
adds the paginate
and page
methods directly to Mongoid::Criteria
, providing an API very similar to the ActiveRecord integration.
Setup
In your application, require the Mongoid integration file:
require 'mongoid'
require 'will_paginate/mongoid'
# ... your Mongoid setup
Usage
Once required, you can call .paginate
or .page
on any Mongoid criteria object.
# Using the paginate method
@posts = Post.paginate(page: params[:page], per_page: 10)
# Using the chainable page method
@posts = Post.where(published: true).page(params[:page])
# Check pagination attributes
@posts.current_page # => 1
@posts.total_entries # => (total count of matching documents)
@posts.total_pages # => (calculated total pages)
Both integrations ensure that you can use the standard will_paginate
view helpers in your templates regardless of the underlying data store.