title: server-side datatables in Rails
body: <p>I am using server-side processing with DataTables in my Rails 4 app. I have my ajax source returning accurate data records from DB. Paginatation works on the html side, i.e. page 1 showing 1-10 of 800 entries, page 2 showing 11-20 of 800 entries, and so on. However, the actual records in the table are the same 10 results. I don't know if it is just redrawing the table with the same 10 records for each page because I've missed something or what.</p>
  
  <p>Does anyone know why I return the same 10 records for every page? Any insight is much appreciated. Thanks in advance.</p>
  
  <p>Gemfile:</p>
  
  <pre><code>gem 'will_paginate'
  gem 'jquery-datatables-rails', github: 'rweng/jquery-datatables-rails'
  </code></pre>
  
  <p>Controller:</p>
  
  <pre><code>def index
    respond_to do |format|
      format.html
      format.json { render json: HomeownersDatatable.new(view_context) }
    end
  end
  </code></pre>
  
  <p>HomeownersDatatable:</p>
  
  <pre><code>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 &gt; 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
  </code></pre>
  
  <p>end</p>
  
  <p>JS to Initailize table:</p>
  
  <pre><code>$(document).ready(function() {
    $('#homeowners_admin_table').DataTable({
      "pagingType": "full_numbers",
      "stateSave": true,
      "processing": true,
      "serverSide": true,
      "ajax": $('#homeowners_admin_table').data('source'),
    });
  });
  </code></pre>