Ruport官方网站:http://www.rubyreports.org/
本例中将介绍Ruby报表的简单开发
开发环境
OS:WindowsXP
Ruby:Ruby1.8.7
Rails:Rails2.3.5
Mysql:Mysql5.0.9
IDE:Rubymine2.0.1
一、安装gem
安装命令
gem install ruport
gem install ruport-util
gem install acts_as_reportable
二、创建数据库
database: dbdevelopment
username: crystal
password: crystal
host: localhost
三、创建Rails工程RailsRuport
1)配置database.yml,内容如下:
development:
adapter: mysql
encoding: utf8
reconnect: false
database: dbdevelopment
pool: 5
username: crystal
password: crystal
host: localhost
2)通过scaffold映射Products表
参数为 Product title:string description:string price:integer
3)修改routes.rb
修改
map.resources :products
为
map.resources :products,:collection=>{:save_as_report=>:get}
表示当遇到save_as_report时,用get方式,否则默认方式将跳转到show.html执行查询
在最后添加
require "rubygems"
require "ruport"
四、修改Product.rb
为Model添加acts_as_reportable方法
修改后代码如下:
class Product < ActiveRecord::Base
acts_as_reportable
set_primary_key "product_id"
end
五、修改products_controller.rb
1)修改index方法为如下:添加Report的输出应用
def index
@products = Product.all
@table = Product.report_table(:all,:only=>['title','description'])
@grouping = @table.to_group('title')
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @products }
end
end
2)添加save_as_report方法,实现Report的保存应用
def save_as_report
puts 'Save Pdf!'
send_data Product.report_table(:all,:only=>['title','description']).to_pdf, :type => "application/pdf",
:filename => "books.pdf"
end
六、 修改app/view/products/index.html.erb
在界面上显示Report绘制的table,在最后添加如下代码:
<h2>Report Table</h2>
<%= @grouping.to_html %>
<br />
<%= link_to 'Save As Report', :controller=>"products",:action=>"save_as_report"%>
演示效果: