2

这是我第一次使用数据表。我希望能够在我的项目表中显示记录并按每个字段排序。我正在关注这个 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>

项目.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

如果有人有任何意见,我将不胜感激。谢谢。

4

1 回答 1

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

于 2013-07-16T13:16:49.290 回答