在rails中使用FusionCharts生成报表

来源:互联网 发布:火星潮牌淘宝 编辑:程序博客网 时间:2024/04/28 08:49
  1. 集成charts(其实相当于Java中准备FusionCharts的lib):
    • 把目录FusionChartsFree\Code\FusionCharts拷贝到ruby项目下的public目录;
    • 把文件FusionChartsFree\Code\FusionCharts\FusionCharts.js拷贝到ruby项目下的public\javascripts目录;
    • 把文件FusionChartsFree\Code\RoR\Libraries\fusioncharts_helper.rb拷贝到ruby项目下的app\helper目录;
  2. 修改app/views/employees/index.html.erb文件,在最后一个link处添加:
    • <td><%= link_to 'Time Chart', {:action=>'view_timesheet_chart',:id=>employee.id} %></td>
    • 启动WEBrick:C:\ruby\TimeTrackerApplication>ruby script/server
    • 打开浏览器:http://localhost:3000/employees,一个scaffold的页面出来了,可以添加一些employee实例数据
  3. 给app\controllers\employees_controller.rb添加代码:

    def view_timesheet_chart
     
       start_date= "2008-12-01"
     
       end_date="2008-12-07"
     
       @employee_id = params[:id]
     
       employee_details_with_timesheets = Employee.find_with_timesheets_in_date_range(@employee_id,start_date,end_date)
     
       if(!employee_details_with_timesheets.nil?)
     
           @employee_details_with_timesheets =employee_details_with_timesheets[0]
     
       else
     
         @employee_details_with_timesheets =nil;
     
       end
     
       headers["content-type"]="text/html"
    end

  4. 在app\models\employee.rb中添加代码:

    def self.find_with_timesheets_in_date_range(id, start_date, end_date)
     
       conditions="employees.id =? and timesheets.log_date between ? and ?"
     
       employee_details_with_timesheets=self.find(:all, :include=>'timesheets', :conditions=> [conditions,id,start_date,end_date], :order=>'log_date asc')
     
       return employee_details_with_timesheets
    end

  5. 在app/views/employees下新建文件view_timesheet_chart.html.erb
    <%= javascript_include_tag "FusionCharts"%><% # The xml is obtained as a string from builder template. str_xml = render "employees/timesheet_data" #Create the chart - Column 3D Chart with data from strXMLrender_chart '/FusionCharts/FCF_Column3D.swf' , '' , str_xml , 'TimeChart' , 650 , 400 ,false , false do -%><% end -%>
  6. 在app/views/employees下新建文件timesheet_data.builder

    require 'builder'

    xml = Builder::XmlMarkup.new(:indent=>0)
    options = {
    :caption=>'Time Tracker Chart',
    :subcaption=>'For Employee '+ @employee_details_with_timesheets.name 
      ,
    :yAxisName=>'Hours Spent',
    :xAxisName=>'Day',
    :showValues=>'1',
    :formatNumberScale=>'0',
    :numberSuffix=>' hrs.'
    }
    xml.graph(options) do
     
     for timesheet in @employee_details_with_timesheets.timesheets do
     
        log_day = timesheet.log_date.strftime('%a')
     
        xml.set(:name=>log_day,:value=>timesheet.hours_spent,:color=>''+get_FC_color)
     
     end
    end

  7. 修改app\helpers\application_helper.rb,添加代码:
    require 'fusioncharts_helper' include FusionChartsHelper
  8. 在我的浏览器http://localhost:3000/employees/view_timesheet_chart/1上,可以看到这么一副图片:

image


0 0
原创粉丝点击