我是数据表中的新手,我想插入一个带有服务端处理和其他一些功能的数据表。
我跟着this tutorial,以便在我的应用中插入我的数据表并且它有效。
这是我的app / assets / datatables / addresses_datatable.rb文件:
class AddressesDatatable
delegate :params, :h, :link_to, :number_to_currency, to: :@view
def initialize(view)
@view = view
end
def as_json(options = {})
{
sEcho: params[:sEcho].to_i,
iTotalRecords: addresses.count,
iTotalDisplayRecords: addresses.total_entries,
aaData: data
}
end
private
def data
addresses.map do |address|
[
h(address.user_id),
h(address.first_name),
]
end
end
def addresses
@addresses ||= fetch_addresses
end
def fetch_addresses
addresses = Address.order("#{sort_column}").page(page).per_page(per_page)
if params[:sSearch].present?
addresses = addresses.where("user_id like first_name like :search", search: "%#{params[:sSearch]}%")
end
addresses
end
def page
params[:iDisplayStart].to_i/per_page + 1
end
def per_page
params[:iDisplayLength].to_i > 0 ? params[:iDisplayLength].to_i : 10
end
def sort_column
columns = %w[user_id first_name]
columns[params[:iSortCol_0].to_i]
end
end
这是我的app / views / addresses / index.html.erb文件:
<h1>User's addresses</h1>
<table id="addresses" class ="display" data-source= "<% user_addresses_path(format:"json")%>">
<thead>
<tr>
<th>User id</th>
<th>first anme</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
这是我的app / asset / javascript / addresses.js文件:
$(document).ready(function() {
var oTable = $('#addresses').dataTable({
sPaginationType: "full_numbers",
bSortClasses: false,
bProcessing: true,
bServerSide: true,
sAjaxSource: $('#addresses').data('source')
});
} );
这是我的addresses_controller.rb:
class AddressesController < ApplicationController
def index
if signed_in?
respond_to do |format|
format.html
format.json { render json: AddressesDatatable.new(view_context) }
end
end
end
end
当我尝试在this example :中添加一些其他功能到我的数据表时,我的代码不起作用:
$(document).ready(function() {
$('#addresses tbody tr').each( function() {
var sTitle;
var nTds = $('td', this);
var sBrowser = $(nTds[0]).text();
<a href="/ref#sTitle">sTitle</a> = sBrowser+' this is the user s id';
this.setAttribute( 'title', <a href="/ref#sTitle">sTitle</a> );
} );
var oTable = $('#addresses').dataTable({
sPaginationType: "full_numbers",
bSortClasses: false,
bProcessing: true,
bServerSide: true,
sAjaxSource: $('#addresses').data('source')
});
oTable.$('tr').tooltip( {
"delay": 0,
"track": true,
"fade": 250
} );
} );
我尝试了很多不同的例子,每次我设法做的唯一事情就是显示简单的数据表。那是因为我的数据表的服务器端行为吗?
感谢您的帮助。
Clément