Mihika
Mihika

Reputation: 535

How to customise the Kaminari URL to include only certain parameters?

I am currently using kaminari for pagination in my project. The url getting generated contains the other parameters as well in addition to the page parameter.

For example, I am using the following to generate my next page url:

path_to_next_page(items, params: params)

This gives me something as follows:

/items?param1=value1&page=1

However, I want only the page parameter to be visible, not the other parameters:

/items?page=1

I tried the following code, but it still gives me the URL with all the parameters:

path_to_next_page(items, params: {page: params['page']})

I also went through this question, and tried the following for the individual page links:

paginate items, params: {page: params['page']}

However, this also generates the URL with all the parameters.

Is there any way to generate the URL with only the page parameter present?

Upvotes: 3

Views: 1853

Answers (2)

Shadwell
Shadwell

Reputation: 34774

The normal use case for pagination is that you do want all the other parameters (you want the nth page of the same results) which is why it's a little hard to remove the other parameters in the request.

The parameters you pass into the paginate call are merged into the current page parameters to generate the links. That means that you can remove parameters by setting their value to nil if you know what they are called, e.g.

= paginate @items, params: { param1: nil }

You could do this programmatically if you wanted to remove all params from the pagination link but you'd need to be careful of 'special' parameters, i.e. you probably want to ignore :controller and :action for example. E.g.

# Get a list of params we want to nullify
params_to_remove = params.keys.select { |param| ![:action, :controller, :page].include?(params) }

# Create a hash of those params mapped to nil
paging_params = params_to_remove.inject({}) { |param, hsh| hsh[param] = nil; hsh }

= paginate @items, params: paging_params

Upvotes: 5

mechnicov
mechnicov

Reputation: 15298

In your controller:

class ItemsController < ApplicationController
  ITEMS_PER_PAGE = 10

  def index
    @items = Item.page(params[:items_page]).per(ITEMS_PER_PAGE)
  end
end

And in your view:

= paginate @items, param_name: :items_page

Now it will add to your params items_page.

E.g. /items?items_page=1

Upvotes: 0

Related Questions