据推测,不需要进行大量配置 - docs。宝石似乎不起作用。相关代码:
的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
错误:
NoMethodError - 未定义的方法`page'对于会员:班级
答案 0 :(得分:1)
错误消息指出您无法分页。此外,在分页数据集上调用count
不正确。相反,首先向类中添加一些选择条件,然后尝试分页结果。关于Mongoid,一个例子是:
@paginated_users = User.where(:age.gte => 10).page(10)
默认情况下,kaminari每页返回25个项目,您可以通过附加per(desired number of items per page)
方法来更改它,
@paginated_users = User.where(:age.gte => 10).page(10).per(5)
最后,请确保在相应的视图文件中添加<%= paginate @paginated_users %>
(在web.rb中声明的相同变量名,其中包含要在视图中分页的数据集)。
答案 1 :(得分:0)
以下对我有用:
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
在Gemfile中:
gem 'mongoid'
gem 'kaminari-mongoid'
gem 'kaminari-sinatra'