Ruby array, javascript and json issue
I am unable to get a highcharts plugin to render a chart in a rails application: http://github.com/loudpixel/highcharts-rails
I believe it has something to do with the sql queries to the database placed in a ruby array, which the javascript is unable to intepret. This is what I have:
def panels
pass = Student.find_by_sql('SELECT COUNT(*) FROM students WHERE student_state = 1')
fail = Student.find_by_sql('SELECT COUNT(*) FROM students WHERE student_state = 2')
student_data = [
{:name => 'Pass', :y => pass},
开发者_如何学运维 {:name => 'Fail', :y => fail}
]
pie_label_formatter = '
function() {
if (this.y > 15) return this.point.name;
}'
pie_tooltip_formatter = '
function() {
return "<strong>" + this.point.name + "</strong>: " + this.y + " %";
}'
@pie_chart =
Highchart.pie({
:chart => {
:renderTo => "pie-chart-container",
:margin => [50, 30, 0, 30]
},
:plotOptions => {
:pie => {
:dataLabels => {
:formatter => pie_label_formatter,
:style => {
:textShadow => '#000000 1px 1px 2px'
}
}
}
},
:series => [
{
:type => 'pie',
:data => student_data
}
],
:subtitle => {
:text => 'April 2010'
},
:title => {
:text => 'Student Status Chart'
},
:tooltip => {
:formatter => pie_tooltip_formatter
},
})
Note if I put this: :data => student_data.to_json It actually returns a json string of my query as text in the browser. Also, if I hard code values (e.g. :y => 1), it will render the chart properly. However, any database query will not render the chart properly. So I'm not sure exactly what the issue is. Any suggestions? Thanks.
You probably want to use count
instead of find_by_sql
:
pass = Student.count(:conditions => ['student_state = ?', 1])
fail = Student.count(:conditions => ['student_state = ?', 2])
find_by_sql
will return you an array of Student
objects. count
will return you the number of rows matching the conditions.
精彩评论