Rails开发表单生成器:提取count结果值填充ChartJS/Google Chart
提取统计值填充图表data字段的方案
嘿,你已经搞定了统计结果的第一步,接下来把这些数值塞进ChartJS或者Google Chart其实很简单,我分几种场景给你讲清楚:
1. 单个问题的基础提取方式
首先假设你在Controller里已经通过.count得到了各个选项的统计值,比如:
# 在你的Controller动作里(比如results动作) def results # 假设你的问题选项是4、2、1,对应统计各个选项的回答数 @option_4_count = Response.where(question_id: params[:id], answer: 4).count @option_2_count = Response.where(question_id: params[:id], answer: 2).count @option_1_count = Response.where(question_id: params[:id], answer: 1).count end
给ChartJS传值
在View的ChartJS脚本里,直接嵌入这些实例变量就行:
const ctx = document.getElementById('form-result-chart').getContext('2d'); new Chart(ctx, { type: 'bar', // 可以换成你需要的图表类型,比如pie data: { labels: ['选项4', '选项2', '选项1'], // 对应选项的显示文本 datasets: [{ label: '回答数量', // 直接把Controller里的统计值塞进来 data: [<%= @option_4_count %>, <%= @option_2_count %>, <%= @option_1_count %>], backgroundColor: ['#ff6384', '#36a2eb', '#ffce56'], borderWidth: 1 }] }, options: { scales: { y: { beginAtZero: true } } } });
给Google Chart传值
Google Chart的写法类似,把统计值嵌入到数据数组里:
google.charts.load('current', {'packages':['corechart']}); google.charts.setOnLoadCallback(drawChart); function drawChart() { var data = google.visualization.arrayToDataTable([ ['选项', '回答数'], ['选项4', <%= @option_4_count %>], ['选项2', <%= @option_2_count %>], ['选项1', <%= @option_1_count %>] ]); var options = { title: '表单问题结果统计' }; var chart = new google.visualization.PieChart(document.getElementById('chart-div')); chart.draw(data, options); }
2. 更高效的批量/动态处理方案
你提到后续要遍历所有问题做批量处理,那用数组和哈希来统一管理统计值会更方便,还能减少数据库查询次数:
Controller里优化统计逻辑
用group(:answer)一次查询就能拿到所有选项的统计结果:
def results # 一次查询获取当前问题所有选项的回答数,返回哈希 { 选项值: 数量 } @response_counts = Response.where(question_id: params[:id]).group(:answer).count # 按你需要的顺序(4、2、1)提取数值,没有的选项默认0 @target_options = [4, 2, 1] @chart_data = @target_options.map { |opt| @response_counts[opt] || 0 } end
View里直接用数组传值
不管是ChartJS还是Google Chart,都可以把数组转成JSON直接传入:
// ChartJS 示例 data: <%= @chart_data.to_json %>, labels: <%= @target_options.map { |opt| "选项#{opt}" }.to_json %>
// Google Chart 示例 var dataRows = [['选项', '回答数']].concat( <%= @target_options.zip(@chart_data).to_json %> ); var data = google.visualization.arrayToDataTable(dataRows);
小提示
- 记得给图表容器(比如
<canvas id="form-result-chart"></canvas>或者<div id="chart-div"></div>)设置好宽高,不然图表可能显示不正常 - 如果是批量处理多个问题,可以把每个问题的统计数据整理成数组,循环渲染对应的图表就行
内容的提问来源于stack exchange,提问作者user9007028
相关产品推荐
相关产品推荐

