Discover how to comply with Rails conventions and manage sorting in a ruby class before returning the data as json to DataTables. If you're dealing with a large volume of records, it's best practice to opt for server-side processing over client-side processing as it offers better performance (the example below demonstrates server-side processing):
The user#index action should be:
def index
respond_to do |format|
format.html
format.json { render json: UsersDatatable.new(view_context) }
end
end
Create a subfolder named datatables within your app folder and include this .rb file:
#app/datatables/users_datatable.rb Note that it's named users_datatable! Rails will automatically determine the correct class lookup path because of this.
class UsersDatatable
delegate :params, :h, :link_to, to: :@view
def initialize(view)
@view = view
end
def as_json(options = {})
{
sEcho: params[:sEcho].to_i,
iTotalRecords: User.count,
iTotalDisplayRecords: users.total_entries,
aaData: data
}
end
private
def data
users.map do |user|
[
user.created_at.strftime("%d-%b-%y")
]
end
end
def users
@users ||= fetch_users
end
def fetch_users
users = User.all.order("created_at DESC")
users = users.page(page).per_page(per_page)
if params[:search].present? && params[:search]["value"].present?
users = users.where("email like :search", search: "#{params[:search]["value"]}%")
users
end
def page
params[:start].to_i/per_page + 1
end
def per_page
params[:length].to_i > 0 ? params[:length].to_i : 10
end
def sort_column
columns = %w[created_at ]
columns[params[:order]["0"]["column"].to_i]
end
def sort_direction
params[:order]["0"]["dir"] == "desc" ? "desc" : "asc"
end
end
Your corresponding users view index.html.erb
should look like this:
<div class='table-responsive'>
<table id='reg_req_data_table' data-source="<%= users_path(params.merge!(format: :json).deep_symbolize_keys)%>">
<thead>
<tr>
<th>Created On:</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#reg_req_data_table').DataTable({
"serverSide": true,
"ajax": {url: '<%= users_path(params.merge!(format: :json).deep_symbolize_keys)%>', type: "POST"},
"processing": true
}),
});
</script>
Take note of the empty table body tags. With server-side processing, DataTables retrieves information via json, which is provided by the UsersDatatable class.