【问题标题】:Ruby array, javascript and json issueRuby 数组、javascript 和 json 问题
【发布时间】:2010-04-01 22:21:21
【问题描述】:

我无法使用 highcharts 插件在 rails 应用程序中呈现图表: http://github.com/loudpixel/highcharts-rails

我相信这与对放置在 ruby​​ 数组中的数据库的 sql 查询有关,javascript 无法解释。这就是我所拥有的:

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
        },
    })

请注意,如果我这样说: :data => student_data.to_json 它实际上将我的查询的 json 字符串作为浏览器中的文本返回。 此外,如果我对值进行硬编码(例如:y => 1),它将正确呈现图表。 但是,任何数据库查询都不会正确呈现图表。所以我不确定到底是什么问题。 有什么建议?谢谢。

【问题讨论】:

    标签: javascript jquery ruby-on-rails ajax json


    【解决方案1】:

    您可能想使用count 而不是find_by_sql:

    pass = Student.count(:conditions => ['student_state = ?', 1])
    fail = Student.count(:conditions => ['student_state = ?', 2])
    

    find_by_sql 将返回一个Student 对象数组。 count 将返回匹配条件的行数。

    【讨论】:

      猜你喜欢
      • 2021-05-02
      • 1970-01-01
      • 2016-10-14
      • 1970-01-01
      • 2018-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多