嗨,我真的很困惑,我在我的 Rails 应用程序中使用 highcharts,并试图获取一个柱形图来显示我在数据库中与女性用户进行比较的男性用户数量,但似乎无法弄清楚如何获取要读取的数据我的用户数据库表。这是我的用户模型
def self.gender_analysis(gender)
User.where(:gender => MALE).count
User.where(:gender => FEMALE).count
end
这是我的 user.js 文件,我在其中创建图表
$(function(){
new Highcharts.Chart({
chart:{
renderTo: "pie_chart",
type:"column"
},
title: { text: "Gender" },
xAxis: { type: "percent correct"},
yAxis: {
title: { text: "Gender" }
},
series: [{
data: <%= users.each do |user| %>
}]
});
});
我的用户 view.html.erb 看起来像
<div id="pie_chart" style="width:568px; height:300px;"></div>
<h1>Listing users</h1>
<table>
<thead>
<tr>
<th>Number</th>
<th>Gender</th>
<th>Hobby</th>
<th>Created</th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<% @users.each do |user| %>
<tr>
<td><%= user.number %></td>
<td><%= user.gender %></td>
<td><%= user.hobby %></td>
<td><%= user.created_at %></td>
我是 Rails 开发新手,非常感谢您提供的任何帮助
最佳答案
很简单:
在您的 View
中,我的意思是在您的html.erb
中放置:
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
并添加脚本
:
$(function () {
$('#container').highcharts({
chart: {
type: 'column'
},
title: {
text: 'Total User'
},
subtitle: {
text: 'Source: Unknown'
},
xAxis: {
categories: ['Male', 'Female'],
title: {
text: null
}
},
yAxis: {
min: 0,
title: {
text: 'Total Number',
align: 'high'
},
labels: {
overflow: 'justify'
}
},
tooltip: {
valueSuffix: ''
},
plotOptions: {
bar: {
dataLabels: {
enabled: true
}
}
},
credits: {
enabled: false
},
series: [{
name: 'Users',
data: [<%= User.where(:gender => 'MALE').count %>, <%= User.where(:gender => 'FEMALE').count %>]
}]
});
});
还可以在这里查看 fiddle 。
祝你编码愉快! :)
关于javascript - Rails 和 Highcharts 柱形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22612587/