2012-07-25 45 views
0

我試圖實現演示如何使用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

+0

我已經瞭解了一些關於這個問題的知識,並將在一篇新文章中討論如何配置與DataTables jQuery插件接口的部分。 – rixter 2012-07-27 22:24:08

+0

#rixter你有沒有發現如何使用ajax對dataTables中的相關列進行排序? – Reddirt 2013-11-13 15:36:42

回答

1

我不知道這是否是它,但你的類與資本G A基因型的方法,它應該是全部小寫。

+0

謝謝!那擺脫了那一個錯誤...現在對其他DataTables錯誤... – rixter 2012-07-27 21:29:13