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(page, _)
  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!

Bonus Section

Ok, so now you’ve implemented the above javascript and you’ve found that this thing is working everywhere! But you may not want that to happen. What do you do?

  • You could limit the scope of the javascript operation, so that it only works if a particular form is found.

  • You could limit the scope of when the javascript is run: so that it runs only on certain controller actions.

  • And lastly, you may want the pagy method overridden only in certain specific situations. Likely the overriding of the pagy methods will coincide only when you want the custom javascript to work.

Hope this works for you!

Written on October 9, 2019