Search code examples
htmlruby-on-railsrubypaginationkaminari

Choosing how many results per page through drop down menu


I use the kaminari pagination gem. I can restrict the results per page to 6. This is an example of my pagination in my products_controller:

def index
  @products = Product.order(:title).page(params[:page]).per(6)
end

But rather than hard coding the "6" in the pagination code, I want the user to be able to change this through the user interface view. I want a drop down menu on the view so that the user can select either "3", "6", or "9". How can I do this? I'm guessing it might involve an instance variable to store the user's selection but I'm not sure, can anyone help? I have this drop down menu in my application.html.erb:

<div id="per-page">
  <select>
    <option value="3">3</option>
    <option value="6">6</option>
    <option value="9">9</option>
  </select>
</div>

Solution

  • Add a name (e.g. 'per') to your select field, e.g.:

    <select name="per"> ... </select>
    

    You might also want look into using select_tag, which will help you make sure that the appropriate option is selected based on the user's selection.

    and then modify:

    Product.order(:title).page(params[:page]).per(params.fetch(:per, '6').to_i)
    

    which will get the user's selection (or '6' if none is selected), and coerce it to an integer (I'm not sure if this coercion is necessary for Kaminari).

    Yes, you will probably need a "Go" button. You should be able to just wrapper your select field like:

     <form>
       <div id="per-page"> ... </div>
       <button>Go!<button>
     </form>
    

    which should work because the default action of a form is the current page.

    Assuming that you are using jQuery and that your select field has an ID of per, you could also omit the button (though you still need the form), and in JavaScript do:

    $('#per').on('change', function() {
      $(this).closest('form').submit();
    });
    

    Some debugging suggestions

    Put <%= debug params %> somewhere towards the bottom of application.html.erb (but inside body).

    Try manually adding the per param to your URL, e.g., localhost:3000/search?per=3.