2013-02-13 87 views
0

我有index.html.erb看起来如此: enter image description here数据导出成csv文件

的时候,我想从我的表导出所有日期到CSV文件中的用户按“应用”按钮(和保存它)。

我在reports_controller.rb下一行定义:

require 'csv' 

和我经过AJAX所有参数到控制器(给函数更新)。

现在

START_DAY = 的开始一天,用户选择

END_YEAR = 末一年,用户在我更新功能选择

,我试图创建csv文件。为了在两个日期之间在我的表中进行搜索,我创建了两个变量:start_date和end_date。

start_date = YYYY-MM-DD(while:YYYY是start_year,MM是start_month,DD是start_day)。

END_DATE类似于起始日期(但有:END_YEAR,END_MONTH和END_DAY)

所以这是我更新功能:

def update 
    @start_day = params[:start_day] 
    @start_month = params[:start_month] 
    @start_year = params[:start_year] 

    @end_day = params[:end_day] 
    @end_month = params[:end_month] 
    @end_year = params[:end_year] 

    # the format of start_date and end_date will be: "YYYY-MM-DD" 
    @start_date = @start_year + "-" + @start_month + "-" + @start_day 
    @end_date = @end_year + "-" + @end_month + "-" + @end_day 

    # get all the transactions between start_date to end_date 
    @transactions = BillingTransaction.find(:all, :conditions =>["date(created_at) BETWEEN ? AND ? ", @start_date, @end_date]) 

    # create the csv file 
    csv_string = CSV.generate do |csv| 
     # insert the headers 
     csv << ["transaction_type", "payment_method"] 
     # run all over the transactions 
     @transactions.each do |user| 
      # each of transactions is inserted into the csv file 
      csv << [BillingTransaction.transaction_type, BillingTransaction.payment_method] 
     end 
    end   

    # save it as 'BillingTransaction.csv' 
    send_data csv_string, 
    :type => 'text/csv; charset=iso-8859-1; header=present', 
    :disposition => "attachment; filename=BillingTransaction.csv" 
end 

回答

4

首先,它不应该是在update方法,因为它违反了RESTful原则。您可以创建一个可以称为transactions的自定义方法,或类似的东西。

因为它不会修改任何东西,并且会产生一个CSV,所以它可以作为GET方法工作。当然,您需要修改路线以使此方法可见。

这也是一个好主意,从参数上创建一个Date对象,如:

@start_date = Date.new(@start_year.to_i, @start_month.to_i, @start_day.to_i) 
@end_date = Date.new(@end_year.to_i, @end_month.to_i, @end_day.to_i) 

,而不是建筑的字符串。

而在each块,你应该增加的实际值:

@transactions.each do |transaction| 
    # each of transactions is inserted into the csv file 
    csv << [transaction.transaction_type, transaction.payment_method] 
end 

最后,你不需要使用实例变量(与@符号前缀),而您不想使用这些变量在你的意见。

所以这里没有什么需要加上前缀@,

+0

谢谢!!!我让你建议我都搞得方法事务可见,由:资源:报告做 集合做 得到:tarnsactions 结束 结束 ,改变AJAX方法是:阿贾克斯$({ \t \t网址: '/报告/交易', \t \t类型: 'GET', \t \t数据:{START_DAY:$( “START_DAY ”)ATTR(“ 值 ”),START_MONTH:$(“。START_MONTH”)ATTR (“value”),start_year:$(“。start_year”)。attr(“value”),end_day:$(“。end_day”)。attr(“value”),end_month:$(“。end_month”)。 attr(“value”),end_year:$(“。end_year”)。attr(“value”)} \t \t}); 现在是什么?我按了“申请”,没有任何反应。 – 2013-02-13 14:24:08

+0

检查日志请求是否由浏览器完成。 – 2013-02-13 15:23:08