我试图实现演示如何使用DataTables的Railscast 340,它看起来像我的项目的一个真棒宝石。如何解决DataTables gem中的这个JSON方法?
当然,我的模型是不同的;但是贝茨先生构建的数据表类(非常快)为了执行服务器端处理,相当复杂。我获得了源代码,并基本上试图跟随。我的观点与零记录(但有> 10,000条记录),但不会中断。
然而,这里是从轨道服务器输出的错误消息指出之前停止:
NameError (undefined local variable or method `genotypes' for #<GenotypesDatatable:0xa9e852c>):
app/datatables/genotypes_datatable.rb:12:in `as_json'
app/controllers/genotypes_controller.rb:8:in `block (2 levels) in index'
app/controllers/genotypes_controller.rb:6:in `index'
在此之前只是,似乎有此JSON错误,启动:
Started GET "/genotypes.json?sEcho=1&iColumns=8&sColumns=&iDisplayStart=0&iDisplayLength=10&mDataProp_0=...
基因型控制器的相关部分看起来是这样的:
def index
respond_to do |format|
format.html
format.json { render json: GenotypesDatatable.new(view_context) }
end
end
我的基因型模型看起来像:
class Genotype < ActiveRecord::Base
attr_accessible :allele1, :allele2, :run_date
belongs_to :gmarkers
belongs_to :gsamples
end
我的数据表类如下。这是从贝茨代码,修改(最有可能不正确地)与我的基因型模式来取代他的产品型号:
class GenotypesDatatable
delegate :params, :h, :link_to, to: :@view
def initialize(view)
@view = view
end
def as_json(options = {})
{
sEcho: params[:sEcho].to_i,
iTotalRecords: Genotype.count,
iTotalDisplayRecords: genotypes.total_entries,
aaData: data
}
end
private
def data
genotypes.map do |genotype|
[
link_to(genotype.name, genotype),
h(genotype.category),
h(genotype.released_on.strftime("%B %e, %Y")),
genotype.run_date
]
end
end
def Genotypes
@Genotypes ||= fetch_Genotypes
end
def fetch_genotypes
genotypes = Genotype.order("#{sort_column} #{sort_direction}")
genotypes = genotypes.page(page).per_page(per_page)
if params[:sSearch].present?
genotypes = genotypes.where("name like :search or category like :search", search: "%#{params[:sSearch]}%")
end
genotypes
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[gmarker gsample allele1 allele2 run_date]
columns[params[:iSortCol_0].to_i]
end
def sort_direction
params[:sSortDir_0] == "desc" ? "desc" : "asc"
end
end
如何解决(或修复!)这个错误非常感激任何提示! (获取这方面的工作为我的项目将是真棒!)
TIA, rixter
我已经了解了一些关于这个问题的知识,并将在一篇新文章中讨论如何配置与DataTables jQuery插件接口的部分。 – rixter 2012-07-27 22:24:08
#rixter你有没有发现如何使用ajax对dataTables中的相关列进行排序? – Reddirt 2013-11-13 15:36:42