Welcome to ajax-datatables-rails

DataTables is a plug-in for the jQuery Javascript library. It is a highly flexible tool, based upon the foundations of progressive enhancement, and will add advanced interaction controls to any HTML table. For more details look at home page This gem fully supports DataTables behavior and easily integrates to rails app. No more need to write JS or Ruby code, just setup your model datatable.

Description

This gem is based on DataTables idiom so It fully supports DataTable.

How-to project

I always build admin page with some data presenting and I love to use DataTable in my projects. But It's to hard to build so many table with server-side pagination, ordering & searching. But now we have this tool! And Today I am going to show usage of this gem with a super easy pattern.

Basic usage

Let's suppose that we have 2 models: countries and cities. So every country has many cities. we build rails app.

$ rails new how-to

$ bin/rails g model country name:string iata:string

$ bin/rails g model city name:string iata:string timezone:string country:references

$ bin/rails g controller cities index

$ rake db:migrate

Gemfile

gem 'ajax-datatables-rails', github: 'ajahongir/ajax-datatables-rails', branch: 'v-0-4-0'
gem 'rails_script'
gem 'js-routes'
gem 'responders' # if you are using rails 4.2+

And then execute:

$ bundle

Initialization third-party libs

rails_script

After bundling you need to run the initial installation generator for rails_script:

$ rails g rails_script:install and include <%= include_rails_script %> in application layout.

js-routes

Add //= require js-routes in your application.js and after clear your cache $ rake tmp:cache:clear

DataTables

Adding latest version of DataTables and style in application layout:

<link rel="stylesheet" href="//cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css" >
<script src="//cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>

Javascript

I add some defaults for my DataTables in global.coffee:

$ ->
  $.extend $.fn.DataTable.defaults,
    searching: true
    ordering: true
    deferRender: true
    lengthMenu: [10, 25, 50, 100]
    serverSide: true

    initComplete: ->
      $('.filters input, .filters select', @).on 'change', (e) =>
        th = $(e.target).closest("th")
        @api().column(th.index()).search($(e.target).val()).draw()

and add these lines in to cities.coffee

class App.Cities extends App.Base

  index: ->
    $ ->
      $('#dataTable').dataTable
        ajax: Routes.cities_index_path()
        columns: [
            data: "id"
          ,
            data: "name"
          ,
            data: "iata"
          ,
            data: "custom_column"
          ,
            data: "country_name"
        ]

Model Datatable

Generating Datatable for model City:

$ bin/rails generate datatable City

Well, we have a app/datatables/city_datatatble.rb file, lets define model fields:

class CityDatatable < AjaxDatatablesRails::Base

  def view_columns
    @view_columns ||= {
      id: { source: "City.id", cond: :eq },
      name: { source: "City.name" },
      custom_column: { source: "custom_column", cond: filter_custom_column_condition },
      iata: { source: "City.iata" },
      country_name: { source: "City.country_id", cond: filter_country_condition },
    }
  end

  private
  def data
    records.map do |city|
      {
        id: city.id,
        name: city.name,
        iata: city.iata,
        country_name: city.country.try(:name),
        custom_column: city[:custom_column]
      }
    end
  end

  def get_raw_records
    City.select('cities.*, timezone AS custom_column').includes(:country)
  end

  def filter_country_condition
    ->(column) { column.table[column.field].eq(column.search.value.to_i + 1) }
  end

  def filter_custom_column_condition
    ->(column) { ::Arel::Nodes::SqlLiteral.new(column.field.to_s).matches("#{ column.search.value }%") }
  end
end

Controller

Don't forget to return response with our Datatable in controller:

class CitiesController < ApplicationController
  respond_to :html, :json

  def index
    respond_to do |format|
      format.html
      format.json do
        render json: CityDatatable.new(view_context)
      end
    end
  end
end

View

Last thing to is adding table in out cities/index.html.erb

<div class="table-responsive">
  <table id="dataTable" class="table table-striped table-bordered" cellspacing="0" width="100%">
    <thead>
      <tr class="filters">
        <th><input/></th>
        <th><input/></th>
        <th><input/></th>
        <th><input/></th>
        <th>
          <%= collection_select(:city, :country_id, Country.all, :id, :name, include_blank: true) %>
        </th>
      </tr>
      <tr>
        <th>Id</th>
        <th>Name</th>
        <th>IATA</th>
        <th>Timezone</th>
        <th>Country</th>
      </tr>
    </thead>
    <tbody></tbody>
  </table>
</div>

$ bin/rails s

That is it!

Requirements

The gem supports ruby 2.0 and higher, rails 3.2 and higher versions.

Sample project

Here is how-to project

Authors and Contributors

Feel free to fork & contribute or leave a feedback if you have any issues.