b-brankovics
b-brankovics

Reputation: 93

ruby on rails will_paginate change default link

In the routes.rb I set lists#index as the root:

root to: "lists#index"

I would like will_paginate to create page hrefs pointing to /?page=# instead of /lists?page=#. To create the paginate links I have the following line in the "lists#index" file:

<%= will_paginate @lists %>

Upvotes: 2

Views: 1447

Answers (3)

Cathy Mc
Cathy Mc

Reputation: 91

In this particular case the links are influenced by the order of the routing instructions in the routes.rb file.

If you place the line

    root to: "lists#index"

at the top of routes.rb then will_paginate will generate links to /?page=# without the need for a custom renderer.

This can be found in the FAQs for the module in coursera.

Upvotes: 1

b-brankovics
b-brankovics

Reputation: 93

The solution was indeed a custom renderer. Thanks Ayush!

The following helped me to solve it: how-to-customize-the-will-paginate-links-with-images

I created a file: app/helpers/will_paginate_helper.rb with the following content:

module WillPaginateHelper
  class RootedLinkRenderer < WillPaginate::ActionView::LinkRenderer
    protected
    def link(text, target, attributes = {})
      if target.is_a? Fixnum
        attributes[:rel] = ""
        target = "/?page=#{target}"
      end
      attributes[:href] = target
      tag(:a, text, attributes)
    end
  end
end

Finally, I updated the index file and replaced:

<%= will_paginate @lists %>

with:

<%= will_paginate @lists, renderer: WillPaginateHelper::RootedLinkRenderer %>

So the href is http://localhost:3000/?page=2 and not http://localhost:3000/lists?page=2.

Upvotes: 4

Don
Don

Reputation: 531

What I understand from your question that you are trying to create a custom renderer, although I have never used it, but for that you need to override the link method of renderer. here is the link to the original code might be of some help - https://github.com/voormedia/paginary/blob/master/lib/paginary/helpers/pagination_helper.rb

Upvotes: 1

Related Questions