我有使用数据表的rails应用程序。我正在使用jquery-datatables-rails gem。
我有一个index.html.erb,如下所示:
<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>
我有一个产品控制器,如下所示:
@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
返回以下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"}]}
我还有一个products.js文件:
jQuery(function() {
return $('#products').dataTable({
sPaginationType: "full_numbers",
bJQueryUI: true,
bProcessing: true,
bServerSide: true,
sAjaxSource: $('#products').data('source')
});
});
数据表正在显示,但在加载后会出现一个警告弹出窗口: DataTables警告(表ID ='产品'):从第0行的数据源请求未知参数'0'
我该如何解决这个问题?谢谢大家的帮助!
答案 0 :(得分:1)
<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')
});
});