Search code examples
rubypaginationsinatrakaminari

How to use Kaminari pagination gem with Sinatra and Mongoid?


Presumably, not a whole lot of configuration is required - docs. The gem doesn't seem to work. Relevant code:

Gemfile:

source 'https://rubygems.org'

ruby '2.2.4'

gem 'sinatra'
gem 'thin'
gem 'slim'
gem 'json'
gem 'mongoid'
gem 'kaminari'

web.rb:

require 'sinatra'
require 'json'
require 'mongoid'
require 'kaminari'

# Mongoid class
class Affiliate
  include Mongoid::Document
  field :name, type: String
end

# MongoDB connection info and whatnot
Mongoid.load!('mongoid.yml', :development)

get '/kaminari' do
  puts Affiliate.page(1).count
end

Error:

NoMethodError - undefined method `page' for Affiliate:Class


Solution

  • The error message states you can't page a class. Also, calling count on paginated data set isn't a correct use. Instead, first add some selection criteria to the class and then try to page the results. With respect to Mongoid, an example would be:

    @paginated_users = User.where(:age.gte => 10).page(10)
    

    By default, kaminari returns 25 items per page, you can change that by appending a per(desired number of items per page) method like so,

    @paginated_users = User.where(:age.gte => 10).page(10).per(5)   
    

    Lastly, make sure you add a <%= paginate @paginated_users %> (the same variable name declared in your web.rb that contains the dataset to be paginated in the view) in your corresponding view file.