我似乎無法找到這個簡單需求的答案:如何告訴Rails和DataTables關於相關的數據表?這是基於Railscast 340。 (Ryan Bates警告說服務器端處理比較複雜,確實是這樣!)如何判斷DataTable如何通過ActiveRecord處理關聯的數據表?
我對Rails的經驗還不是太熟悉,所以我仍然在學習使用各種find()方法來告訴ROR相關的數據活動記錄;但我的任務的本質是基因型,其中在視圖中的棘手位是index.html.erb視圖文件顯示:
def index
respond_to do |format|
format.html
format.json { render json: GenotypesDatatable.new(view_context) }
end
end
見下面的滿級GenotypesDatatables的;這直接在/ app文件夾下的新類中。
我需要顯示/編輯三種模型的數據:基因型,gmarkkers和gvision。我還需要顯示來自gsamples和gmarkers的與基因型相關的兩個模型數據。
的模型構造,如:
class Gmarker < ActiveRecord::Base
attr_accessible :marker
has_many :genotypes, :dependent => :delete_all
...
class Genotype < ActiveRecord::Base
attr_accessible :allele1, :allele2, :run_date
belongs_to :gmarkers
belongs_to :gsamples
...
class Gsample < ActiveRecord::Base
belongs_to :gupload
has_many :genotypes, :dependent => :delete_all
attr_accessible :box, :labid, :subjectid, :well
如可以從網絡服務器這個輸出錯誤信息中可以看出,問題就出在沒有得到正確的數據關聯: ...
CACHE (0.0ms) SELECT COUNT(*) FROM "genotypes"
Genotype Load (10.5ms) SELECT "genotypes".* FROM "genotypes" ORDER BY allele1 asc LIMIT 10 OFFSET 0
Completed 500 Internal Server Error in 255ms
NameError (undefined local variable or method `f' for #<GenotypesDatatable:0x9833ad4>):
app/datatables/genotypes_datatable.rb:24:in `block in data'
app/datatables/genotypes_datatable.rb:21:in `data'
app/datatables/genotypes_datatable.rb:14:in `as_json'
app/controllers/genotypes_controller.rb:7:in `block (2 levels) in index'
app/controllers/genotypes_controller.rb:5:in `index'
...
數據應該是使用服務器端處理來準備的,但這會導致在DataTable中傳遞給jQuery的JSON數組。 JSON數組被班上的DataTable準備:
class GenotypesDatatable
delegate :params, :h, :link_to, to: :@view
def initialize(view)
@view = view
end
def as_json(options = {})
# This is what feeds directly into DataTables
{
sEcho: params[:sEcho].to_i,
iTotalRecords: Genotype.count,
iTotalDisplayRecords: genotypes.total_entries,
aaData: data
}
end
private
def data
genotypes.map do |genotype|
[
# Note: h is shorthand for html_escape
h(Gmarker.find(f.gmarkers_id).marker),
h(Gsample.find(f.gsamples_id).labid),
h(Gsample.find(f.gsamples_id).subjectid),
h(Gsample.find(f.gsamples_id).box),
h(Gsample.find(f.gsamples_id).well),
h(genotype.allele1),
h(genotype.allele2),
h(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("labid like :search or category like :search", search: "%#{params[:sSearch]}%")
end
genotypes
end
...
肯定會欣賞這裏的指針;感覺就像沒有地圖或手電筒,我迷失在叢林中!
感謝, 裏克·凱西
約翰:非常感謝!這絕對有幫助!當你知道如何時,一切都如此簡單! --rick – rixter 2012-08-06 20:40:29