2012-01-02 29 views
0

Rails 2.35/Ruby 1.87创建图表 - 在JS语句中插入Rails变量的JSON/XML优势?

我一直在尝试jqplot

对于Fusion Charts,我总是使用为视图呈现XML的构建器文件。使用jqPlot,如果我可以简单地构建数据字符串并将其插入生成图的JavaScript,是否有任何理由来呈现JSON文件(等)?

此外,我找不到任何jqPlot Rails的例子,只是做了一些事情。我很好奇我是如何写得更好的(或者如果我在这里确定的话)。

谢谢!

CONTROLLER 
    --------------------- 
def provisioned_accounts 
    sql = %Q{ 
      SELECT day_of, provisioned_accounts from daily_provisioned_accounts_rollup 
      } 
    graph_data = DailyProvisionedAccountsRollup.find_by_sql(sql) 

    @graph_data = '' 
    x = 0 
    graph_data.each do |g| 
     x += 1 
     if x == 1 
     @graph_data += "['" + g.day_of.to_s + "', " + g.provisioned_accounts.to_s + "]" 
     else 
     @graph_data += ", ['" + g.day_of.to_s + "', " + g.provisioned_accounts.to_s + "]" 
     end 
    end 
    end 

    VIEW 
    --------- 
    <div id="chart1" style="height:300px; width:800px;"></div> 

    <script type="text/javascript"> 
    $(document).ready(function(){ 
     var line1=[<%= @graph_data %>]; 
     var plot1 = $.jqplot('chart1', [line1], { 
      title:'Provisioned Accounts', 
      axes:{ 
      xaxis:{ 
       renderer:$.jqplot.DateAxisRenderer, 
       tickOptions:{ 
       formatString:'%b&nbsp;%#d' 
       } 
      }, 
      yaxis:{ 
       tickOptions:{ 
       formatString:'%.0f' 
       } 
      } 
      } 
     }); 
    }); 
</script> 

回答

1

有几件事情我会在这里有所不同。

移动你的find_by_sql到一个方法上DailyProvisionedAccountsRollup称为是这样的:

class DailyProvisionedAccountsRollup < ActiveRecord::Base 
    ... 

    def self.summary 
    all.map do |record| 
     [ record.day_of, record.provisioned_accounts ] 
    end 
    end 
end 

然后,在你的控制你可以这样做:

def provisioned_accounts 
    @graph_data = DailyProvisionedAccountsRollup.summary 
end 

最后,在你看来,你只需要使用@graph_data.to_json

<div id="chart1" style="height:300px; width:800px;"></div> 

<script type="text/javascript"> 
    $(document).ready(function(){ 
    var line1=<%= @graph_data.to_json %> 
    var plot1 = $.jqplot('chart1', [line1], { 
     title:'Provisioned Accounts', 
     ... 

这都是未经测试的co德,但它应该让你开始清理你的控制器。

+0

谢谢 - 在那里学到了很多东西。 – Reno 2012-01-02 12:53:59