the_
the_

Reputation: 1173

Datatable rails issue

I have rails application that is using datatables. I'm using the jquery-datatables-rails gem.

I have a index.html.erb that looks like:

<table id='products' class="display" data-source="<%= store_products_path(format: "json") %>">
  <thead>
    <tr>
      <th>Store Id</th>
      <th>Created At</th>
      <th>Updated At</th>
    </tr>
  </thead>
  <tbody>

  </tbody>
</table>

I have a products controller that looks like:

@products = Product.all
respond_to do |format|
    format.html
    format.json do
      render :json=> {
        "sEcho"               => params[:sEcho].to_i,
        "iTotalRecords"       => @products.count,
        "iTotalDisplayRecords"=> @products.count,
        "aaData"              => @products.as_json(
          :only => [:store_id, :created_at, :updated_at]
        )
      }
    end
  end

that returns the following json:

{"sEcho":0,"iTotalRecords":2,"iTotalDisplayRecords":2,"aaData":[{"store_id":128,"created_at":"2014-02-19T04:30:43.455Z","updated_at":"2014-02-19T04:30:43.455Z"},{"store_id":128,"created_at":"2014-02-22T04:39:08.708Z","updated_at":"2014-02-22T04:39:08.708Z"}]}

I also have a products.js file:

jQuery(function() {
   return $('#products').dataTable({
     sPaginationType: "full_numbers",
     bJQueryUI: true,
     bProcessing: true,
     bServerSide: true,
     sAjaxSource: $('#products').data('source')
   });
});

The datatable is showing up, but after it loads an alert popup comes up that says: DataTables warning (table id = 'products'): Requested unknown parameter '0' from the data source for row 0

How can I fix this? Thanks for all help!

Upvotes: 0

Views: 319

Answers (1)

Allerin
Allerin

Reputation: 1108

<table id='products' class="display" data-source="<%= store_products_path(format: "json") %>">
  <thead>
    <tr>
      <th data-column='store_id'>Store Id</th>
      <th data-column='created_at'>Created At</th>
      <th data-column='updated_at'>Updated At</th>
    </tr>
  </thead>
  <tbody>

  </tbody>
</table>


jQuery(function() {
   columns = []
   $('#products').find('thead tr th').each(function(i, th){
     columns.push({mData: $(th).data('column')})
   });
   return $('#products').dataTable({
     sPaginationType: "full_numbers",
     bJQueryUI: true,
     bProcessing: true,
     bServerSide: true,
     aoColumns: columns,
     sAjaxSource: $('#products').data('source')
   });
});

Upvotes: 1

Related Questions