Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
A

ajax-datatables-rails

> 后端框架
Open source

A wrapper around DataTable's ajax methods that allow synchronization with server-side pagination in a Rails app

601 stars0 likes0 views
WebsiteGitHub

About

A wrapper around DataTable's ajax methods that allow synchronization with server-side pagination in a Rails app

ajax-datatables-rails

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 :

  • Rails: 7.1 / 7.2 / 8.0 / 8.1
  • Ruby: 3.1 / 3.2 / 3.3 / 3.4 / 4.0 (Rails 8.0 and 8.1 require Ruby >= 3.2)
  • Databases: MySQL 8 / SQLite3 / Postgresql 16 / Oracle Free 23
  • Adapters: sqlite / mysql2 / postgres / postgis / oracle

trilogy and sqlserver are implemented (type casting and NULLS LAST ordering) but are not currently exercised in CI.

Description

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-rails is 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).

Installation

Add these lines to your application's Gemfile:

ruby
gem 'ajax-datatables-rails'

And then execute:

bash
$ bundle install

We assume here that you have already installed jQuery DataTables.

You can install jQuery DataTables :

  • with importmap-rails (bin/importmap pin datatables.net-dt), the Rails 7+ default
  • with jsbundling-rails (yarn add datatables.net-dt)
  • by adding the assets manually (in vendor/assets)
  • with the legacy Rails webpacker gem (see here for more infos)

Migrating from an older version of the gem ? See the migration guide.

Note

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.

Quick start (in 5 steps)

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 Email 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 :

  1. Generate the datatable class
  2. Build the View
  3. Customize the generated Datatables class
  4. Setup the Controller action
  5. Wire up the Javascript

1) Generate the datatable class

Run the following command:

bash
$ rails generate datatable User

This 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.

2) Build the View

You should always start by the single source of truth, which is your html view.

  • Set up an html with a and ``
  • Add in your table headers if desired
  • Don't add any rows to the body of the table, DataTables does this automatically
  • Add a data attribute to the `` tag with the url of the JSON feed, in our case is the users_path as we're pointing to the UsersController#index action
xml
">
  
    

      ID
      First Name
      Last Name
      Email
      Brief Bio
    

  
  
  

3) Customize the generated Datatables class

a. Declare columns mapping

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:

ruby
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" },
  }
end

Notes : 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 field
  • Proc 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 :

ruby
def view_columns
  @view_columns ||= {
    population: { source: 'City.population', cond: ->(column, value) { column.table[column.field].gt(value.to_i) } },
  }
end

Silent 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 :

ruby
class MyDatatable  (o) { o.upcase } },
    bio:        { source: "User.bio" },
  }
end

The object passed to the lambda is the search value.

b. Map data

Then we need to map the records retrieved by the get_raw_records method to the real values we want to display :

ruby
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
end

Deprecated: 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.

ruby
def data
  records.map do |record|
    [
      record.id,
      record.first_name,
      record.last_name,
      record.email,
      record.bio
    ]
  end
end

The 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 :

erb

  
  
    
  

…

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.

Columns syntax

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.

ruby
# 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' }
  }
end

Associated and nested models

The 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:

ruby
'course_types.name'
'courses.name'
'contacts.full_name'
'competency_types.name'
'events.title'
'events.event_start

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Rubydatatablesjqueryjquery-datatablesrails

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category后端框架
PricingOpen source

> Related tools

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架