ruby-on-railsrubyruby-on-rails-5will-paginate

Guard against invalid page number (0) for will_paginate?


The will_pagify gem will_paginate will throw an error if you send it the param page=0. Is there a better way than declaring page = nil (or 1) if param[:page] =~ /^[0]{,}$/? Hoping this is to support zero-index pages and I can disable this with a function parameter.

*There may be other invalid inputs I haven't tested. Strings go to nil.

Update:

Trying to avoid:

begin
  model = Model.where(...).paginate(page: params[:page])
  <additional code>
rescue
  model = Model.where(...).paginate(page: '1')
  <redo additional code again or use function***>

vs.

current_page = clean_page(params[:page])
model = Model.where(...).paginate(page: current_page)

Solution

  • You can leverage what WillPaginate has already done to handle all cases as follows:

    def clean_page(page)
      begin 
        WillPaginate::PageNumber(page)
      rescue WillPaginate::InvalidPage
        1  
      end 
    end 
    

    and that will handle all the same issues because you are leveraging their validation process and anything that fails defaults to page 1.

    Working Example