A wrapper around DataTable's ajax methods that allow synchronization with server-side pagination in a Rails app
A wrapper around DataTable's ajax methods that allow synchronization with server-side pagination in a Rails app
Important : This gem implements the server-side processing protocol introduced in DataTables 1.10. It works with any DataTables version speaking that protocol (1.10.x and 2.x).
It's tested against :
trilogy and sqlserver are implemented (type casting and NULLS LAST ordering) but are not currently exercised in CI.
DataTables is a nifty jQuery plugin that adds the ability to paginate, sort, and search your html tables. When dealing with large tables (more than a couple of hundred rows) however, we run into performance issues. These can be fixed by using server-side pagination, but this breaks some DataTables functionality.
ajax-datatables-railsis a wrapper around DataTables ajax methods that allow synchronization with server-side pagination in a Rails app. It was inspired by this Railscast. I needed to implement a similar solution in a couple projects I was working on, so I extracted a solution into a gem.Joel Quenneville (original author)
I needed a good gem to manage a lot of DataTables so I chose this one :)
Nicolas Rodriguez (current maintainer)
The final goal of this gem is to generate a JSON content that will be given to jQuery DataTables. All the datatable customizations (header, tr, td, css classes, width, height, buttons, etc...) must take place in the javascript definition of the datatable. jQuery DataTables is a very powerful tool with a lot of customizations available. Take the time to read the doc.
You'll find a sample project with real world examples here : https://github.com/jbox-web/ajax-datatables-rails-sample-project
This gem handles only the server side. For the client side, its companion gem datatables-factory builds the HTML table and the javascript for you (see below).
Add these lines to your application's Gemfile:
gem 'ajax-datatables-rails'And then execute:
$ bundle installWe assume here that you have already installed jQuery DataTables.
You can install jQuery DataTables :
importmap-rails (bin/importmap pin datatables.net-dt), the Rails 7+ defaultjsbundling-rails (yarn add datatables.net-dt)vendor/assets)Migrating from an older version of the gem ? See the migration guide.
AjaxDatatablesRails only supports ActiveRecord as ORM for performing database queries.
The AjaxDatatablesRails::ORM namespace exists so other backends (Sequel, Mongoid...) could be plugged in,
but none is implemented and none is currently being worked on.
If you'd be interested in contributing to speed development, please open an issue and get in touch.
The following examples assume that we are setting up ajax-datatables-rails for an index page of users from a User model,
and that we are using Postgresql as our db, because you should be using it. (It also works with other DB, see below)
The goal is to render a users table and display : id, first name, last name, email, and bio for each user.
Something like this:
| ID | First Name | Last Name | Brief Bio | |
|---|---|---|---|---|
| 1 | John | Doe | [email protected] | Is your default user everywhere |
| 2 | Jane | Doe | [email protected] | Is John's wife |
| 3 | James | Doe | [email protected] | Is John's brother and best friend |
Here the steps we're going through :
Run the following command:
$ rails generate datatable UserThis will generate a file named user_datatable.rb in app/datatables.
Open the file and customize in the functions as directed by the comments.
Take a look here for an explanation about the generator syntax.
You should always start by the single source of truth, which is your html view.
with a and ``users_path as we're pointing to the UsersController#index action">
ID
First Name
Last Name
Email
Brief Bio
First we need to declare in view_columns the list of the model(s) columns mapped to the data we need to present.
In this case: id, first_name, last_name, email and bio.
This gives us:
def view_columns
@view_columns ||= {
id: { source: "User.id" },
first_name: { source: "User.first_name", cond: :like, searchable: true, orderable: true },
last_name: { source: "User.last_name", cond: :like, nulls_last: true },
email: { source: "User.email" },
bio: { source: "User.bio" },
}
endNotes : by default orderable and searchable are true and cond is :like.
cond can be :
:like, :start_with, :end_with, :string_eq, :string_in for string or full text search:eq, :not_eq, :lt, :gt, :lteq, :gteq, :in for numeric:date_range for date range:null_value for nil fieldProc for whatever (see here for real example)Any other value raises AjaxDatatablesRails::Error::InvalidSearchCondition.
About the numeric conditions : the search value must be an integer that fits the column (the gem checks the column byte size to avoid a Postgresql value out of range error). A non-integer or out-of-range value produces an always-false condition instead of a SQL error.
About :null_value : the search value drives the direction of the test. The special value
!NULL searches for non-null rows (WHERE col IS NOT NULL), anything else searches for
null rows (WHERE col IS NULL).
About Proc : the lambda receives the Column object and the (formatted) search value,
and must return an Arel node :
def view_columns
@view_columns ||= {
population: { source: 'City.population', cond: ->(column, value) { column.table[column.field].gt(value.to_i) } },
}
endSilent fallbacks : a column whose source is a Model.field pair is only searchable if
field is a real database column, and only orderable if field is a real database column or
an explicit sort_field is given. A source pointing at an association name (e.g. User.posts)
would otherwise generate an invalid WHERE / ORDER BY — such a column is silently dropped from
filtering and sorting rather than raising. If a column mysteriously refuses to sort or search,
check that its source names a column and not an association.
The nulls_last param allows for nulls to be ordered last. You can configure it by column, like above, or by datatable class :
class MyDatatable (o) { o.upcase } },
bio: { source: "User.bio" },
}
endThe object passed to the lambda is the search value.
Then we need to map the records retrieved by the get_raw_records method to the real values we want to display :
def data
records.map do |record|
{
id: record.id,
first_name: record.first_name,
last_name: record.last_name,
email: record.email,
bio: record.bio,
DT_RowId: record.id, # This will automagically set the id attribute on the corresponding
in the datatable
}
end
endDeprecated: You can either use the v0.3 Array style for your columns :
This method builds a 2d array that is used by datatables to construct the html table. Insert the values you want on each column.
def data
records.map do |record|
[
record.id,
record.first_name,
record.last_name,
record.email,
record.bio
]
end
endThe drawback of this method is that you can't pass the DT_RowId so it's tricky to set the id attribute on the corresponding in the datatable (need to be done on JS side).
See here if you need to use view helpers like link_to, mail_to, etc...
HTML escaping : every leaf value returned by data is run through ERB::Util.html_escape
before being serialized. Markup you generate on purpose (with link_to, a decorator...) is
already html_safe and passes through untouched; a raw String containing `
$('#users-datatable').dataTable
processing: true
serverSide: true
ajax:
url: $('#users-datatable').data('source')
pagingType: 'full_numbers'
columns: [
{data: 'id'}
{data: 'first_name'}
{data: 'last_name'}
{data: 'email'}
{data: 'bio'}
]
# pagingType is optional, if you want full pagination controls.
# Check dataTables documentation to learn more about
# available options.
…ruby gem 'datatables-factory'
and in `package.json` :
```json
{
"dependencies": {
"@jbox-web/datatables-factory": "^1.0.0"
}
}The view then declares the table and its filters in Ruby, instead of raw HTML :
…
ruby
class UserDatatable 1
# per-column search value sent by DataTables for that column
column_data(:first_name) # => 'John'Useful when get_raw_records needs to branch on what the user is filtering on.
You can mix several model in the same datatable.
Suppose we have the following models: User, PurchaseOrder,
Purchase::LineItem and we need to have several columns from those models
available in our datatable to search and sort by.
# we use the ModelName.column_name notation to declare our columns
def view_columns
@view_columns ||= {
first_name: { source: 'User.first_name' },
last_name: { source: 'User.last_name' },
order_number: { source: 'PurchaseOrder.number' },
order_created_at: { source: 'PurchaseOrder.created_at' },
quantity: { source: 'Purchase::LineItem.quantity' },
unit_price: { source: 'Purchase::LineItem.unit_price' },
item_total: { source: 'Purchase::LineItem.item_total' }
}
endThe previous example has only one single model. But what about if you have some associated nested models and in a report you want to show fields from these tables.
Take an example that has an Event, Course, CourseType, Allocation, Teacher, Contact, Competency and CompetencyType models. We want to have a datatables
report which has the following column:
'course_types.name'
'courses.name'
'contacts.full_name'
'competency_types.name'
'events.title'
'events.event_startNo open issues yet, or sync has not completed.