2017-01-15 22 views
0

解決在Rails中爲圖表分組記錄?

我有一個餅圖:

enter image description here

data: [<% HomeworkStudent.where(:school_user_id => current_user.school_user.id).each do | homework_student| %> 
      [<%= homework_student.homework.classmodule.subject.to_json.html_safe %>, <%= homework_student.difficulty.to_json %>], 
      <% end %>] 
    }] 

的數據繪製精細,但我期待組 「看病難」 的問題。換句話說,在圖表上只應該有數學和藝術。這是高圖表。

我也試圖通過我的模型以下不同的方法,但它不工作:

homework.rb

def self.getData 
    data = [] 
    self.subjectnames.each do |type2| 
     data << Hash["name", type2, "y", self.type2_count(type2)] 
    end 
    data 
    end 

... 
private 

def self.subjectnames 
    Classmodule.pluck(:homework_id).uniq 
    end 

    def self.type2_count(type2) 
    HomeworkStudent.where(difficulty: type2).count 
    end 

然後圖表像這樣的:

Controller 

@data = Homework.getData() 

View: 

data: <%= @data.to_json.html_safe %> 

後一條路線是理想的路線,但由於涉及不同的模型,這有點令人困惑。

有3個模型:Classmodule包含主題名稱,homework_student包含難度欄和homework_id欄。

homework.rb 
has_many :homework_students, :class_name => 'HomeworkStudent', dependent: :destroy 
    belongs_to :classmodule, :class_name => 'Classmodule', :foreign_key => :subject 

classmodule.rb 
    has_many :homeworks, :class_name => 'Homework' 

homework_student.rb: 
belongs_to :classmodule, :class_name => 'Classmodule', :foreign_key => :subject 

雖然不是很理想,我寧願現在就做正確我的做法在頂部的作品,但我只是想知道如何按主題分組的結果?如果我不得不通過模型的這個任何建議?

謝謝!

解決

由於紅寶石賽車:

在控制器:

@data = {} 
     HomeworkStudent.where(:school_user_id => current_user.school_user.id).each do |homework_student| 
     label = homework_student.homework.classmodule.subject 
     value = homework_student.difficulty.to_i 
    @data[label] = (@data[label]) ? (@data[label] + value) : value 
end 

在圖表上圖:

data: <%= @data.to_a.to_json.html_safe %> 

回答

1

沒有進入模型,我會去這樣的事情:

@data = {} 
HomeworkStudent.where(:school_user_id => current_user.school_user.id).each do |homework_student| 
    label = homework_student.homework.classmodule.subject 
    value = homework_student.difficulty 
    @data[label] = (@data[label]) ? (@data[label] + value.to_i) : value.to_i 
end 

現在@data看起來有點像這樣:

@data 
# {"art"=>90, "math"=>200} 
@data.to_a 
# [["art", 90], ["math", 200]] 

這是很多喜歡你的需要。現在你只需要將它轉換爲JSON和HTML安全

newdata = @data.map {|subject, difficulty| [subject.to_json.html_safe, difficuty.to_json]} 

但你並不真的需要這樣做。所以,你的紅寶石陣列發送到JS:

data: <%= @data.to_a.inspect.html_safe %> 

或者更好的是:

data: <%= @data.to_a.to_json.html_safe %> 
+0

你好,非常感謝,我更新的OP與您的解決方案,我得到一個錯誤......有在難度列中爲零值... – Co2

+0

只需添加'to_i',查看我的更新答案。無我爲零 –

+0

謝謝,差不多有!數據:newdata無法正常工作,因此更改爲數據:<%= @ newdata.to_json.html_safe%>並返回數據:[[「\」Maths \「」,「26」],[「\」Art \「」 ,「30」]],正確的格式應該像[「數學」,26] ... – Co2