我有以下代码
# Gemfile
gem 'will_paginate'
# /config/initializers/will_paginate_array.rb
require 'will_paginate/collection'
Array.class_eval do
def paginate(page = 1, per_page = 15)
WillPaginate::Collection.create(page, per_page, size) do |pager|
pager.replace self[pager.offset, pager.per_page].to_a
end
end
end
# /app/controllers/games_controller.rb
def show
@presenter = GamesPresenter.new(json)
@games = @presenter.games.paginate(params[:page], 5)
end
# /app/views/games/index.html.erb
<% @games.each do |game| %>
...
<% end %>
<%= will_paginate @games %>
然而,当我尝试在line @games = @presenter.games.paginate(params[:page], 5)
传递params [:page]时,我params[:page]
为零。有人知道为什么会这样吗? 。如果page.blank添加page = 1?只给我第一页结果..有什么建议吗?
答案 0 :(得分:3)
params[:page]
为nil
。我建议你通过将class_eval更改为
def paginate(page = 1, per_page = 15)
page ||= 1
WillPaginate::Collection.create(page, per_page, size) do |pager|
pager.replace self[pager.offset, pager.per_page].to_a
end
end
当您将nil
作为第一个参数传递时,它将不会使用1
,因为您明确传递了一个值。