我有一个功能,最初以 HTML(报告)显示结果,然后
可以导出为 CSV 和 XLS
这个想法是重用用于呈现 HTML 的查询的结果,导出相同的记录,而无需再次重新运行查询
最接近的实现是这样的:将结果存储在全局变量 $last_consult 中
我在 Ruby 控制器中有以下 INDEX 方法
def index
begin
respond_to do |format|
format.html {
@filters = {}
@filters['email_enterprise'] = session[:enterprise_email] ;
# Add the selected filters
if (params[:f_passenger].to_s != '')
@filters['id_passenger'] = params[:f_passenger] ;
end
if (session[:role] == 2)
@filters['cost_center'] = session[:cc_name]
end
# Apply the filters and assign them to $last_consult that is used
$last_consult = InfoVoucher.where(@filters)
@info_vouchers = $last_consult.paginate(:page => params[:page], :per_page => 10)
estimate_destinations (@info_vouchers)
@cost_centers = fill_with_cost_centers(@info_vouchers)
}
format.csv {
send_data InfoVoucher.export
}
format.xls {
send_data InfoVoucher.export(col_sep: "\t")
}
.export 方法定义如下
class InfoVoucher < ActiveRecord::Base
include ActiveModel::Serializers::JSON
default_scope { order('voucher_created_at DESC') }
def attributes
instance_values
end
#Exporta a CSV o XLS
def self.export(options = {})
column_names = ["...","...","...","...","...",...]
exported_col_names = ["Solicitud", "Inicio", "Final", "Duracion", "Pasajero", "Unidades", "Recargo", "Propina", "Costo", "Centro de costo", "Origen", "Destino", "Proyecto", "Conductor", "Placas"]
CSV.generate(options) do |csv|
csv << exported_col_names
$last_consult.each do |row_export|
csv << row_export.attributes['attributes'].values_at(*column_names)
end
end
end
end
但这种方法只有在查看报告和导出报告之间没有并发用户的情况下才有效,在这种情况下这是不可接受的
我尝试使用会话变量来存储查询结果,但由于查询的结果可能相当大,因此会失败并出现此错误
ActionDispatch::Cookies::CookieOverflow: ActionDispatch::Cookies::CookieOverflow
我读过有关闪存的内容,但不认为它是一个好的选择
您能否为我指明如何保留查询结果(当前存储在 $last_consult 中)的正确方向,并使其可用于 CSV 和 XLS 导出,而无需使用全局或会话变量