#340 DataTables
DataTables makes it easy to convert a plain HTML table into one with pagination, sorting, and searching - all done with JavaScript and jQuery. Here I show how to set this up and use a Rails application as the data source.
- Download:
- source codeProject Files in Zip (84.3 KB)
- mp4Full Size H.264 Video (30.1 MB)
- m4vSmaller H.264 Video (14.9 MB)
- webmFull Size VP8 Video (13.7 MB)
- ogvFull Size Theora Video (37 MB)
Resources
Gemfile
group :assets do gem 'jquery-datatables-rails', github: 'rweng/jquery-datatables-rails' gem 'jquery-ui-rails' end gem 'will_paginate'
app/assets/javascripts/application.js
//= require dataTables/jquery.dataTables
app/assets/stylesheets/application.css
/* *= require jquery.ui.core *= require jquery.ui.theme *= require dataTables/src/demo_table_jui */
app/assets/javascripts/products.js.coffee
jQuery -> $('#products').dataTable sPaginationType: "full_numbers" bJQueryUI: true bProcessing: true bServerSide: true sAjaxSource: $('#products').data('source')
views/products/index.html.erb
<table id="products" class="display" data-source="<%= products_url(format: "json") %>"> <thead> <tr> <th>Product Name</th> <th>Category</th> <th>Release Date</th> <th>Price</th> </tr> </thead> <tbody> </tbody> </table>
products_controller.rb
def index respond_to do |format| format.html format.json { render json: ProductsDatatable.new(view_context) } end end
app/datatables/products_datatable.rb
class ProductsDatatable delegate :params, :h, :link_to, :number_to_currency, to: :@view def initialize(view) @view = view end def as_json(options = {}) { sEcho: params[:sEcho].to_i, iTotalRecords: Product.count, iTotalDisplayRecords: products.total_entries, aaData: data } end private def data products.map do |product| [ link_to(product.name, product), h(product.category), h(product.released_on.strftime("%B %e, %Y")), number_to_currency(product.price) ] end end def products @products ||= fetch_products end def fetch_products products = Product.order("#{sort_column} #{sort_direction}") products = products.page(page).per_page(per_page) if params[:sSearch].present? products = products.where("name like :search or category like :search", search: "%#{params[:sSearch]}%") end products end def page params[:iDisplayStart].to_i/per_page + 1 end def per_page params[:iDisplayLength].to_i > 0 ? params[:iDisplayLength].to_i : 10 end def sort_column columns = %w[name category released_on price] columns[params[:iSortCol_0].to_i] end def sort_direction params[:sSortDir_0] == "desc" ? "desc" : "asc" end end