How to use Kaminari pagination gem with Sinatra an

2019-06-07 21:03发布

问题:

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

回答1:

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.



回答2:

The following worked for me:

require 'mongoid'
require 'kaminari/sinatra'
require 'kaminari/mongoid'


get '/rest/1.0/post' do
  # matches "GET /rest/1.0/post?page=1"
  page_id = params[:page].to_i
  redirect '/rest/1.0/post?page=1' if page_id == 0

  page = Post.page(page_id)

  json(size:         Post.count,
       total_pages:  page.total_pages,
       per_page:     page.limit_value,
       prev_page:    page.prev_page,
       current_page: page_id,
       next_page:    page.next_page,
       data:         page)
end

And in the Gemfile:

gem 'mongoid'
gem 'kaminari-mongoid'
gem 'kaminari-sinatra'