[英]Ruby on Rails, JSON and Highcharts
我试图让 highcharts 图表从表格中自动更新。 目前我正在对每条记录进行如下编码:
<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>
在模型 notes.rb 中:
def self.subject_analysis(subject_type)
Note.where(:subject_type => English).count if subject_type == :english
Note.where(:subject_type => Geography_Class_C).count if subject_type == :Geography_Class_C
Note.where(:subject_type => Maths_Class_B).count if subject_type == :Maths_Class_B
end
类模块模式
t.integer "student_id"
t.string "subject"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
显然这并不理想。 我想要的是柱形图在表中放入新记录时自动更新。 为此,我想我需要在控制器中使用 JSON 并将其传递给 Highcharts。 只是我不知道该怎么做。 任何指导? 谢谢。 如果需要更多信息,我会提供。
您需要 3 个步骤来设置它:
在您的路由文件中为 JSON API 创建一个路由,例如:
get 'highchart-data', to: 'controller_name#action_name'
在控制器中创建一个动作(匹配你刚刚创建的路由):
def action_name @data = [Note.where(:subject_type => 'English').count, Note.where(:subject_type => 'Geography Class C').count, Note.where(:subject_type => 'Maths Class B').count] render json: @data end
在您的 js 文件中,假设您正在使用jQuery
并在您的本地主机上使用端口 3000 运行,从上面创建的路由中获取数据。 在创建series
之前添加此行:
$.getJSON('http://localhost:3000/highchart-data', function(data) { var highChartData = data; });
并series
替换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
那么你的控制器非常简单:
class BarChartController < ApplicationController
def show
@data = Note.highchart_data
end
...
end
至于将 @data 实例变量放入 JS 中,有几种不同的方法。 其中之一可能如下所示:
在您的节目视图中:
<%= javascript_tag do %>
window.highchartDATA = '<%= @data %>';
<% end %>
在你的 JS 中:
...
series: [{
name: 'Number of Notes By Class Module',
data: highchartDATA
}]
...
请注意,此代码是为了说明概念,而不是复制和粘贴。
根据您的评论,我已更新示例代码以使用用户添加的唯一 subject_types。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.