这是我第一次使用dataTables。我希望能够在我的Projects表中显示记录并按每个字段排序。我正在关注此RailCast并使用他们提供的代码。但是,我的页面加载没有错误,但实际记录从未加载到表中 - 它只是无限期地说“处理...”。任何想法会导致什么?我的一些代码:
view / projects / new.html.erb(我的应用程序的索引所指向的位置,以及我希望表格显示的位置)
<table id="projects" class="display" data-source="<%= projects_url(format: "json") %>">
<thead>
<tr>
<th>File</th>
<th>Author</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
projects.js.coffee
jQuery ->
$("#projects").dataTable
bProcessing: true
bServerSide: true
sAjaxSource: $('#projects').data('source')
"aaSorting": [[ 0, "desc" ]]
项目控制器
# GET /projects/new
# GET /projects/new.json
def new
@projects = Project.all
respond_to do |format|
format.html # new.html.erb
format.json { render json: ProjectsDatatable.new(view_context) }
end
end
Projects_datatable.rb
class ProjectsDatatable
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: Project.count,
iTotalDisplayRecords: Project.count,
aaData: data
}
end
private
def data
projects.map do |proj|
[
h(proj.filename),
h(proj.author)
]
end
end
def projects
@projects ||= fetch_projects
end
def fetch_projects
projects = Project.order("#{sort_column} #{sort_direction}")
projects = projects.page(page).per_page(per_page)
if params[:sSearch].present?
projects = projects.where("name like :search or category like :search", search: "%#{params[:sSearch]}%")
end
projects
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[name category released_on price]
columns[params[:iSortCol_0].to_i]
end
def sort_direction
params[:sSortDir_0] == "desc" ? "desc" : "asc"
end
end
我的项目迁移:
class CreateProjects < ActiveRecord::Migration
def change
create_table :projects do |t|
t.string :filename
t.string :location
t.string :author
end
end
end
如果有人有任何意见,我会非常感激。感谢。
答案 0 :(得分:0)
答案肯定有点晚,但我可以看到这些方面的一些错误:
projects = projects.where("name like :search or category like :search", search: "%#{params[:sSearch]}%")
和
columns = %w[name category released_on price]
您必须按文件名,位置,作者替换这些字段。
iTotalDisplayRecords: Project.count,
也错了,用
替换它iTotalDisplayRecords: projects.total_entries,
确保你有will_paginate