Server datatables in Rails

I use server-side processing using DataTables in my Rails 4 application. I have my ajax source returning exact data records from the database. Paginatation works from the html side, i.e. Page 1, showing 1-10 of 800 entries, page 2 shows 11-20 of 800 entries, etc. However, the actual entries in the table are the same 10 results. I don’t know if it just redraws the table with the same 10 records for each page, because I missed something or what.

Does anyone know why I am returning the same 10 records for each page? Any insight is greatly appreciated. Thanks in advance.

Gemfile:

gem 'will_paginate'
gem 'jquery-datatables-rails', github: 'rweng/jquery-datatables-rails'

Controller:

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

HomeownersDatatable:

class HomeownersDatatable
delegate :params, :link_to, to: :@view

def initialize(view)
    @view = view
end

def as_json(options = {})
    {
        sEcho: params[:sEcho].to_i,
        iTotalRecords: Homeowner.count,
        iTotalDisplayRecords: homeowners.total_entries,
        aaData: data,
    }
end

private
def data
    homeowners.map do |homeowner|
        [
            link_to(homeowner.name, @view.edit_admin_homeowner_path(homeowner.id)),
            # (homeowner.name),
            (homeowner.id),
            (homeowner.email),
            (homeowner.address),
            (homeowner.zip_code),
        ]
    end
end

def homeowners
    @homeowners ||= fetch_homeowners
end

def fetch_homeowners
    homeowners = Homeowner.order("#{sort_column} " "#{sort_direction}")
    homeowners = homeowners.page(page).per_page(per_page)
    if params[:sSearch].present?
        homeowners = homeowners.where("name like :search or email like :search", search: "%#{params[:sSearch]}%")
    end
    homeowners
end

def page
    params[:iDisplayStart].to_i/per_page + 1
end

def per_page
    params[:iDisplayLength].to_i > 0 ? params[:iDisplayLength].to_i : 20
end

def sort_column
    columns = %w[id email]
    columns[params[:iSortCol_0].to_i]
end

def sort_direction
    params[:sSortDir_0] == "DESC" ? "DESC" : "ASC"
end

end

JS to initialize the table:

$(document).ready(function() {
  $('#homeowners_admin_table').DataTable({
    "pagingType": "full_numbers",
    "stateSave": true,
    "processing": true,
    "serverSide": true,
    "ajax": $('#homeowners_admin_table').data('source'),
  });
});
+4
1

. , :

$('#table').DataTable({{...}) 

:

$('#table').dataTable({{...}). 

.

0

All Articles