Global and Per-Model Configuration

will_paginate allows you to configure the default number of items per page both globally and on a per-model basis.

Global Configuration

You can set a site-wide default for per_page by setting WillPaginate.per_page. This is best done in an initializer file within your application.

For a Rails application, create a file like config/initializers/will_paginate.rb:

# config/initializers/will_paginate.rb

# Set the default number of items per page to 10
WillPaginate.per_page = 10

This value will be used for any pagination query that does not have a per_page value specified at the model level or in the paginate call itself.

Per-Model Configuration

You can also override the global default for specific models by defining the per_page class method within the model itself.

# app/models/post.rb
class Post < ApplicationRecord
  # Set the number of items per page for the Post model to 20
  self.per_page = 20
end

Now, any call to Post.paginate or Post.page will default to 20 items per page unless explicitly overridden in the method call.

Precedence

The per_page value is determined in the following order of precedence (from highest to lowest):

  1. Method Argument: The value passed directly to the paginate or per_page method.

    Post.paginate(page: 1, per_page: 5) # 5 items per page

  2. Model-Specific Setting: The value set with self.per_page in the model.

    # Assuming self.per_page = 20 in Post model
    Post.paginate(page: 1) # 20 items per page

  3. Global Setting: The value set with WillPaginate.per_page.

    # Assuming WillPaginate.per_page = 10
    User.paginate(page: 1) # 10 items per page (if User has no specific setting)