如何将Kaminari分页宝石与Sinatra和Mongoid一起使用?
大概不需要很多配置-文档.宝石似乎不起作用.相关代码:
Presumably, not a whole lot of configuration is required - docs. The gem doesn't seem to work. Relevant code:
宝石文件:
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-Affiliate:Class的未定义方法页面"
NoMethodError - undefined method `page' for Affiliate:Class
错误消息指出您无法分班课程.另外,在分页数据集上调用count
也不正确.而是,首先向类添加一些选择条件,然后尝试分页结果.关于Mongoid,一个例子是:
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)
默认情况下,kaminari每页返回25个项目,您可以通过添加per(desired number of items per page)
这样的方法来更改它,
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)
最后,请确保在相应的视图文件中添加<%= paginate @paginated_users %>
(在web.rb中声明的相同变量名,其中包含要在视图中分页的数据集).
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.