#240 Search, Sort, Paginate with AJAX
Many administration pages have search, sorting, and pagination on the index page. See how to add all of this including AJAX.
- Download:
- source codeProject Files in Zip (125 KB)
- mp4Full Size H.264 Video (21.7 MB)
- m4vSmaller H.264 Video (14.5 MB)
- webmFull Size VP8 Video (34 MB)
- ogvFull Size Theora Video (30.3 MB)
Resources
bash
rails g jquery:install
Gemfile
gem 'will_paginate', '3.0.pre2' gem 'jquery-rails'
products_controller.rb
def index @products = Product.search(params[:search]).order(sort_column + " " + sort_direction).paginate(:per_page => 5, :page => params[:page]) end
models/product.rb
def self.search(search) if search where('name LIKE ?', "%#{search}%") else scoped end end
helpers/application_helper.rb
def sortable(column, title = nil) title ||= column.titleize css_class = column == sort_column ? "current #{sort_direction}" : nil direction = column == sort_column && sort_direction == "asc" ? "desc" : "asc" link_to title, params.merge(:sort => column, :direction => direction, :page => nil), {:class => css_class} end
products/index.html.erb
<%= form_tag products_path, :method => 'get', :id => "products_search" do %> <p> <%= text_field_tag :search, params[:search] %> <%= submit_tag "Search", :name => nil %> </p> <div id="products"><%= render 'products' %></div> <% end %>
products/_products.html.erb
<%= hidden_field_tag :direction, params[:direction] %> <%= hidden_field_tag :sort, params[:sort] %> <%= will_paginate @products %>
products/index.js.erb
$("#products").html("<%= escape_javascript(render("products")) %>");
application.js
$(function() { $("#products th a, #products .pagination a").live("click", function() { $.getScript(this.href); return false; }); $("#products_search input").keyup(function() { $.get($("#products_search").attr("action"), $("#products_search").serialize(), null, "script"); return false; }); });