Created
December 18, 2014 09:41
-
-
Save pama/65bcf526923d369c258f to your computer and use it in GitHub Desktop.
will_paginate switching page by persisting a search form
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# We need to trigger click event for pagination links and search submit. Also, we need to post | |
# to the entry point when searching, as it will avoid handling the search in 2 different places. | |
# | |
# The submit click event resets the page hidden field. The link event will get the page | |
# number, updates the page hidden field and submits the form. | |
# routes.rb | |
get 'will_paginate', to: 'will_paginate#index' | |
post 'will_paginate', to: 'will_paginate#index' | |
# will_paginate_controller.rb | |
def index | |
page = params[:page] == "" ? nil : params[:page] | |
# note that you should for params[:query] to avoid expensive queries | |
@users = User.where("name LIKE ?", "%#{params[:query]}%") | |
.paginate(page: page, per_page: 5) | |
end | |
# The form | |
<%= form_tag("/will_paginate", id: 'my_form', name: 'my_form') do %> | |
<%= hidden_field_tag :page, params[:page], id: 'page' %> | |
<%= label_tag(:query, 'Search for:') %> | |
<%= text_field_tag(:query, params[:query]) %> | |
<%= submit_tag("Find", id: 'find') %> | |
<% end %> | |
<%= render partial: 'table', locals: {uses: @users} | |
<%= will_paginate @users, id: 'pagination' %> | |
# the script | |
<script> | |
$("#find").click(function() { | |
// resets pagination | |
$("#page").val(""); | |
}); | |
$("#pagination a").click(function() { | |
// get all search form attributes | |
var query = $('#query').val() | |
// whe only want to post if the form has values | |
if (query) { | |
// gets the page attribute from the link we clicked | |
var pos = this.href.search("page="); | |
var page = this.href.substring(pos + 5, this.href.length); | |
// updates the hidden input and submits the form | |
$("#page").val(page); | |
$('#my_form').submit(); | |
return false; | |
} | |
// else, let the GET request happen | |
console.log('GET request'); | |
}) | |
</script> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment