[英]How to configure datatable so that it will order(desc) the records based on the created_date?
我在我的rails
應用程序中使用datatable
到用戶index
頁面。 index
頁面中的第一column
是created_at
。 此column
的data
看起來像Mon, 17-Oct-16
。 我想使這個欄應根據此日期格式進行排序desc
order
。 我怎樣才能做到這一點? 這是我試過的。 但它沒有奏效。
<script type="text/javascript">
$(document).ready(function() {
var index = $('#reg_req_data_table').dataTable({
"order": [[ 1, "desc" ]],
'aoColumnDefs': [{
'bSortable': false
}],
"bLengthChange": false,
"sDom": '<"top"pfl>rt<"bottom"i><"clear">'
});
});
</script>
這個答案將向您展示如何遵循Rails約定並處理ruby類中的排序,然后將其作為json返回到DataTables。 此外,如果您正在處理超過數百條記錄,強烈建議您使用服務器端處理,而不是客戶端處理(此示例將顯示服務器端):
您的用戶#index action應該是:
def index
respond_to do |format|
format.html
format.json { render json: UsersDatatable.new(view_context) }
end
end
您應該在名為datatables的app文件夾中創建一個子文件夾,然后將此.rb文件添加到其中:
#app/datatables/users_datatable.rb Notice it's called users_datatable! Rails will infer the proper class lookup path because of this.
class UsersDatatable
delegate :params, :h, :link_to, to: :@view
def initialize(view)
@view = view
end
def as_json(options = {})
{
sEcho: params[:sEcho].to_i,
iTotalRecords: User.count,
iTotalDisplayRecords: users.total_entries,
aaData: data
}
end
private
def data
users.map do |user|
[
user.created_at.strftime("%d-%b-%y")
]
end
end
def users
@users ||= fetch_users
end
def fetch_users
users = User.all.order("created_at DESC")
users = users.page(page).per_page(per_page)
if params[:search].present? && params[:search]["value"].present?
users = users.where("email like :search", search: "#{params[:search]["value"]}%")
users
end
def page
params[:start].to_i/per_page + 1
end
def per_page
params[:length].to_i > 0 ? params[:length].to_i : 10
end
def sort_column
columns = %w[created_at ]
columns[params[:order]["0"]["column"].to_i]
end
def sort_direction
params[:order]["0"]["dir"] == "desc" ? "desc" : "asc"
end
end
現在您的相應用戶視圖index.html.erb
應為:
<div class='table-responsive'>
<table id='reg_req_data_table' data-source="<%= users_path(params.merge!(format: :json).deep_symbolize_keys)%>">
<thead>
<tr>
<th>Created On:</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#reg_req_data_table').DataTable({
"serverSide": true,
"ajax": {url: '<%= users_path(params.merge!(format: :json).deep_symbolize_keys)%>', type: "POST"},
"processing": true
}),
});
</script>
請注意表body標簽中沒有任何內容。 Serverside處理集數據表通過json接受該信息,這是我們在UsersDatatable類中發送的內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.