服务器端jQuery DataTable错误

时间:2015-08-03 18:48:52

标签: jquery ruby-on-rails ruby ajax datatable

我已经将jQuery DataTable从客户端扩展到服务器端,以便更快地加载1000+数据。

但是我很难实现服务器端搜索,因为所有数据都不会立即加载。

我正在关注railscast(http://railscasts.com/episodes/340-datatables

app/datatables/wine_list_datatable.rb

class WineListsDatatable
  delegate :params, :link_to, :number_to_currency, :content_tag, to: :@view

  def initialize(view)
    @view = view
  end

  def as_json(options = {})
    {
      sEcho: params[:sEcho].to_i,
      iTotalRecords: WineList.count,
      iTotalDisplayRecords: wine_lists.total_entries,
      aaData: data
    }
  end

private

  def data
    wine_lists.map do |wine_list|
      [
        (wine_list.vintage),
        (wine_list.name),
        (wine_list.region),
        (wine_list.country.name),
        (wine_list.wine_maker.name),
        link_to('profile', wine_list.wine_maker),
        (wine_list.score),
        link_to('delete', wine_list, :method => "Delete", data: {confirm: "Are you sure?"}),
        link_to('edit', [:edit, wine_list])
      ]
    end
  end

  def wine_lists
    @wine_lists ||= fetch_wine_lists
  end

  def fetch_wine_lists
    wine_lists = WineList.order("#{sort_column} #{sort_direction}")
    wine_lists = wine_lists.page(page).per_page(per_page)
    if params[:sSearch].present?
      wine_lists = wine_lists.where("name like '%?%'", search: params[:sSearch])
    end
    wine_lists
  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

我感到困惑的是

      wine_lists = wine_lists.where("name like '%?%'", search:  params[:sSearch])

目前,我收到2个错误。

DataTables警告:table id = wine_lists - Ajax错误。有关此错误的详细信息,请参阅http://datatables.net/tn/7

谢谢!

1 个答案:

答案 0 :(得分:0)

该行的语法有错误。 Railscast中的搜索查询是这样的:

products = products.where("name like :search or category like :search", search: "%#{params[:sSearch]}%")

但您的行

wine_lists = wine_lists.where("name like '%?%'", search: params[:sSearch])

解决方案是更改'%?%'

wine_lists = wine_lists.where("name like '%#?%'", params[:sSearch])

或跟随Railscast:

wine_lists = wine_lists.where("name like :search", search: "%#{params[:sSearch]}%")

请注意,jQuery Datatable已更新为1.10,其中参数命名发生了重大变化。它仍然与Railscast中使用的1.9命名兼容,但是如果要升级到1.10,here是参数的新命名参考。