Rails收集JSON数据并将其呈现到Highcharts图中

我试图将标签传递到x轴上的Highcharts柱形图。

目前图表的工作原理是它渲染数据,但x轴标签显示0,1,2,3 …等,这是没有任何渲染时的默认值。

notes_controller:

def dashboard @data = Note.getData() end 

note.rb

 def self.getData data = [] self.subject_types.each do |type| data << self.type_count(type) end data end private def self.subject_types pluck(:subject_type).uniq end def self.type_count(type) where(subject_type: type).count end end 

dashboard.html.erb javascript

 ...series: [{ name: 'Number of Notes By Class Module', data:  }]... 

以上作品很棒,但我如何才能展示标签? 它们应该来自我的表中名为subject_type的列。 我尝试过以下方法:

note.rb:

 def self.getSubjects respond_to do |format| render :json => @note.to_json(:only => [:subject_type]) end 

(我可能这样做完全错了!)

notes_controller.rb:

 def subject @subject = Note.getSubjects() end 

dashboard.html.erb:

 ...series: [{ name: 'Number of Notes By Class Module', data: ,  }]... 

谢谢。 在这里任何帮助,我真的很感激。

为什么要在x-axis打印subject_type ? 图表的axes通常用于测量。 轴可以是线性,对数,日期时间或类别。

根据我的理解,您希望将每个subject_type显示为series name

如果No试试这个

 xAxis: { categories: '<%=raw @subjects.to_json %>' } 

如果Yes试试这个

Highcharts系列对象是一个数组,意味着它可以包含几个系列。 name属性为系列命名。 data属性表示系列值。

这意味着我们的series必须是这样的。

 series: [ {name: 'Subject Type 1', data: [5] }, {name: 'Subject Type 2', data: [6] }, {name: 'Subject Type n', data: [n] }, ] 

你有一个Note表,其中包含subject_type列。 每个note必须包含subject_type 。 您只需要找出成为series name的uniq subject_type以及成为series datasubject_type总数。

你可以这样做:

 def dashboard @series_data = [] @notes = Note.select("id, subject_type, COUNT(*) AS total").group("id, subject_type") # Collect series data that will be show @notes.group_by(&:subject_type).each do |k, v| @series_data << { name: k.titleize, data: [v.size] } end end 

在您的dashboard.html.erb中

 series: <%=raw @series_data.to_json %> 

正如我上面所看到的,你还需要图表title 。 你可以这样做。

 title: { text: "Number of Notes By Class Module" } 

我希望这会有所帮助。

试试这个:

首先,我们将使用您当前的类方法来获取一个subject_types数组:

 def dashboard @data = Note.getData() @subjects = Note.subject_types end 

然后按照Highchats 示例 , xAxis: categories json键是我们需要放置subject标签数组的地方:

 $('#container').highcharts({ chart: { type: 'line' }, //other options ... xAxis: { categories: <%= @subjects %> }, series: [{ name: 'Number of Notes By Class Module', data: <%= @data %> }] });