Rails Serverside Datatables made easy
Installation
Add this line to your application's Gemfile:
gem 'rails_serverside_datatables'
And then execute:
$ bundle
Or install it yourself as:
$ gem install rails_serverside_datatables
Usage
Basic usage
Lets say we have the following model User:
firstname | lastname | score
----------+----------+-------
Jane | Doe | 42
John | Doe | 23
... | ... | ...
To create a datatable you can sort and filter, just create a controller method like this one:
class UsersController < ApplicationController
include RailsServersideDatatables
# ...
def ajax
datatable( [
{ display_name: 'Firstname', expression: :firstname },
{ display_name: 'Lastname', expression: :lastname },
{ display_name: 'Score', expression: :score }
], User.all )
end
# ...
end
Add the required entry to the routes.rb, e.g.:
get '/users/datatable_ajax', to: 'users#ajax'
Now you can reference you datatable by either creating the table on your own and initialize it using datatables... or you just use the following code in your view:
<%= serverside_datatable( users_ajax_path, 'user-table', class: 'my-css-class' ) %>
Computed columns
Let's say you only want to show the name in the form lastname, firstname in one column and double the score adding 'points':
class UsersController < ApplicationController
include RailsServersideDatatables
# ...
def ajax
datatable( [
{ display_name: 'Firstname', expression: [ :lastname, ' ', :firstname ] },
{ display_name: 'Score', expression: [ text_cast( num_op( :score, '*', 2 ) ), ' points' ] }
], User.all )
end
# ...
end
Decorator functions
If you want to display the data in a custom style, you can use structured data (e.g. additional data queried you can then use in the decorator method) and a decorator block.
The structured data can be passed in the config parameter. Every key that is not a predefined parameter like display_name is used as an additional expression queried from the database:
class UsersController < ApplicationController
include RailsServersideDatatables
# ...
def ajax
datatable( [
Column.new( :name, [ :lastname, ' ', :firstname ], display_name: 'Full name', uid: :id ) {
|value, data| view_context.link_to value, user_path( data[:uid] )
},
Column.new( :score, :score, display_name: 'Score' ) {
|value, _| "#{value} points"
}
], User.all )
end
# ...
end
License
The gem is available as open source under the terms of the MIT License.