How To Persist Parameters Over Pagination
Jul 21, 2006I’m a big fan of the pagination functionality built into Rails. I just saves me a lot of time in my Rails projects when I’m dealing with large amounts of tabular data. The one problem is that if you do things like allowing data to be sorted by column pagination isn’t inherently smart enough to play nice. This isn’t spelled out very clearly in the Rails API, so I figured it’d be nice to have an actual example available.
For example: We sort some data in a table by it’s “updated on” column, skip to page 2, and we lose our sorting. Why? Because the parameter used for sorting doesn’t persist across the GET request. We need to make this happen, here’s how.
Rails provides automatic generation of pagination links:
<%= pagination_links(@data_pages) %>
Which will generate links such as:
/my_action?page=2
You can pass in a hash of extra parameters that will be passed along through the GET request. This will allow you to persist any parameters across the pages of data.
<%= pagination_links(
@data_pages,
{:params => {:foo => params[:foo], :bar => params[:bar]}}
) %>
The resulting link will look like:
/my_action?page=2&foo=value&bar=value
And our problem is solved. Simple as that.