Ruby on rails RubyonRails、JSON和Highcharts
我正在尝试从表中自动更新highcharts图形。目前,我正在对每条记录逐一进行编码,如下所示:Ruby on rails RubyonRails、JSON和Highcharts,ruby-on-rails,ruby,json,highcharts,Ruby On Rails,Ruby,Json,Highcharts,我正在尝试从表中自动更新highcharts图形。目前,我正在对每条记录逐一进行编码,如下所示: <script> ... }, series: [{ name: 'Number of Notes By Class Module', data: [<%= Note.where(:subject_type => 'English').count %>, <
<script>
...
},
series: [{
name: 'Number of Notes By Class Module',
data: [<%= Note.where(:subject_type => 'English').count %>, <%= Note.where(:subject_type => 'Geography Class C').count %>, <%= Note.where(:subject_type => 'Maths Class B').count %>]
}]
});
});
</script>
类模块模式
t.integer "student_id"
t.string "subject"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
显然,这并不理想。我想让柱状图在表中放入新记录时自动更新。为此,我认为我需要在控制器中使用JSON并将其传递给Highcharts。只是我不知道怎么做。有什么指导吗?谢谢如果需要更多信息,我将提供。您需要三个步骤进行设置:
get 'highchart-data', to: 'controller_name#action_name'
jQuery
,并在本地主机上运行端口3000,则从上面创建的路由获取数据。在创建系列之前添加此行:
$.getJSON('http://localhost:3000/highchart-data', function(data) {
var highChartData = data;
});
系列中
将数据
行替换为:
data: highChartData
如果“自动更新”的意思是当浏览器刷新时图表总是最新的,那么您不需要使用JSON,并且您的实现可以相对简单 首先,我将把实际的数据编译移到模型本身中。类似这样的内容将构造所需的三元素数组:
class Note < ActiveRecord::Base
...
def self.highchart_data
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
请注意,此代码是为了说明概念,而不是复制和粘贴
更新
根据您的评论,我已经更新了示例代码,以使用用户添加的独特主题类型。多亏了你们两位。让我困惑的是,“英语”、“数学B类”和“地理C类”科目是用户放在表格中的记录。上述情况是否不一样?例如,假设物理是由用户添加的,我希望它只是显示出来,而不必再次触摸代码。非常感谢您的指导。谢谢。肯定更近了。尝试加载仪表板时出现此错误。#xAxis:{categories:[],title:{text:null}的未定义局部变量或方法“subject_types”,我认为x轴应该是这样的?@Co2我已经更新了Note类,使用了三种我已经测试过的类方法。谢谢。视图出现了,但数据没有呈现。我稍后会发布更详细的内容。我只是想知道我之前的评论中是否有类别语法错误。
data: highChartData
class Note < ActiveRecord::Base
...
def self.highchart_data
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
class BarChartController < ApplicationController
def show
@data = Note.highchart_data
end
...
end
<%= javascript_tag do %>
window.highchartDATA = '<%= @data %>';
<% end %>
...
series: [{
name: 'Number of Notes By Class Module',
data: highchartDATA
}]
...