I am trying to create a paginated index view in Rails 3.2 with a drop down menu to select the number of items displayed per page. I am using the will_paginate gem and the pagination function is working great.
However, with my current setup shown below, I am getting validation errors when changing the drop down menu selection. It appears to be trying to create or save a Contact model instead of just making another request to the index action. Any help will be greatly appreciated.
Here is my index action:
def index
#logic here to set per_page value depending on request?
@contacts = Contact.paginate(page: params[:page], :per_page => 20)
end
Here is my index.html.erb view with my attempt at a drop down menu for items per page:
<%= form_tag({ :action => "index", :method => "get" }, { :id => "contacts-index" }) do %>
<%= select_tag(:view, options_for_select([["10", 10], ["25", 25], ["50", 50]]), { :id => "switch-view" }) %>
<% end %>
<% @contacts.each do |contact| %>
<%= contact.first_name %><%= contact.last_name %>
<% end %>
Lastly, here is the jQuery I am using to try to submit the new request to contacts#index when the items per page is changed:
$(document).ready(function() {
$("#switch-view").change(function() {
$("#contacts-index").submit();
});
});
:method => getshould be moved out of the first hash.Without this, it’s doing a post and submitting the ‘method’ as a param. A post to the ‘index’ url will result in the validation errors you’re seeing.