Paginating Search Results using POST Requests From a Complex Form

According to the pagy documentation:

You may need to POST a very complex search form that would generate an URL potentially too long to be handled by a browser, and your page links may need to use POST and not GET. In that case you can try this simple solution:

def pagy_url_for(pagy, page)
  # if you are using an old version of pagy
  # then please ensure the arguments above are inverted:
  # pagy_url_for(page, pagy)
  # because the order of the variables was changed in later versions
  page
end

That would produce links that look like e.g. <a href="2">2</a>. Then you can attach a javascript “click” event on the page links. When triggered, the href content (i.e. the page number) should get copied to a hidden "page" input and the form should be posted.

This blog posts shows you exactly how to do that!

There are many ways to skin a cat - I will present two alternate solutions. Consider choosing what suits you best.

  1. You can do this using j-query, plain javascript, or if you wish,
  2. Use Stimulus JS and Turbo frames to submit and get results.
  3. Using AJAX and turbo streams.
Written on October 9, 2019