params [:page]是零

时间:2013-03-12 14:57:05

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1 will-paginate

我有以下代码

# 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?只给我第一页结果..有什么建议吗?

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,因为您明确传递了一个值。