在Sinatra上使用SEQUEL进行分页结果

时间:2013-06-06 00:21:04

标签: sinatra will-paginate sequel

我正在使用will_paginate并尝试从SEQUEL分页数据集。要求是:

require 'will_paginate'
require 'will_paginate/sequel'
require 'will_paginate/collection'
require 'will_paginate/version'
require 'sequel/extensions/pagination'

红宝石代码是:

get '/candidate' do
     @items = DB[:candidates].order(:id).extension(:pagination).paginate(1, 10)
     erb :candidate
end

在视图中:<%= will_paginate @items %>

数据集正确呈现10条记录,当我点击“2”或“下一步”时,浏览器中的地址变为http://localhost:4567/candidate?page=2,但记录保持不变。实际上,结果没有被分页,我无法通过第1页。

最感谢所有人的帮助。

1 个答案:

答案 0 :(得分:1)

页面的编号和编号。记录在您的示例paginate(1, 10)中是硬编码的,因此它将始终返回包含10条记录的第1页。您需要从查询字符串传递page=2参数。这是通过params helper

完成的
get '/candidate' do
  @items = DB[:candidates].order(:id).paginate(:page => params["page"].to_i, :per_page => 10)
  erb :candidate
end

如果您愿意,还可以通过添加以下代码传递查询字符串中的per_page

get '/candidate' do
   @items = DB[:candidates].order(:id).paginate(:page => params["page"].to_i, :per_page => params["per_page"].to_i)
   erb :candidate
end

如果没有给出,我会为两者添加默认值。我理解you can do this via the library,例如WillPaginate.per_page = 10,但您也可以通过以下途径执行此操作:

get '/candidate' do
  page = params.fetch "page", 1
  per_page = params.fetch "per_page", 10
  @items = DB[:candidates].order(:id).paginate(:page => page.to_i, :per_page => per_page.to_i)
  erb :candidate
end

编辑:在您使用will_paginate提供的Sinatra助手之前我没有注意到(对不起,我生病了!)

我要么在数据集 上调用paginate,要么 获取数据集 - 取消标记 - 并将其传递给帮助程序。所以要么:

get '/candidate' do
  page = params.fetch "page", 1
  per_page = params.fetch "per_page", 10
  @items = DB[:candidates].order(:id).paginate(:page => page.to_i, :per_page => per_page.to_i)
  erb :candidate
end

# in the view
<%= @items %>

或者这个:

get '/candidate' do
  @items = DB[:candidates].order(:id)
  erb :candidate
end

# in the view
<%= will_paginate @items, params %>

编辑:

因此,从what I can see开始,续集paginate方法不会被覆盖或包装/重载,因此its method signature与您使用续集时的情况相同,而不是will_paginate同样。这意味着此代码对我有用:

require 'will_paginate'
require 'will_paginate/sequel'
get '/candidate' do
  page = params.fetch "page", 1
  per_page = params.fetch "per_page", 10
  @items = Repo.db[:candidates].order(:id).paginate(page.to_i, per_page.to_i)
  haml :candidate
end

在haml视图中。

- @items.each do |i|
  = i[:title]

由于方法签名相同,我不确定使用will_paginate而不是Sequel的paginate会有什么好处。我找不到让Sinatra帮手工作的方法。

相关问题