在rails 3.2中下载CSV

时间:2014-08-06 15:44:30

标签: ruby-on-rails csv

我正在尝试将一些模型数据从搜索页面下载到csv文件。以下是相关代码:

配置/ application.rb中

require 'csv'

控制器

  def find_by_registration_date
    @registration_date = params[:registration_date]
    @registrations = Registration.where("DATE(created_at) = ? ", @registration_date)
    respond_to do |format|
      format.html
      format.csv { send_data Registrations.to_csv(@registrations) }
    end
  end

模型

  def self.to_csv(options = {})
    CSV.generate(options) do |csv|
      csv << column_names
      all.each do |registration|
        csv << registration.attributes.values_at(*column_names)
      end
    end
  end

编辑:当我尝试这个时,我收到错误:

TypeError in RegistrationsController#find_by_registration_date

can't convert ActiveRecord::Relation into Hash

Rails.root: /home/johnmlocklear/railsApps/nso
Application Trace | Framework Trace | Full Trace

app/models/registration.rb:43:in `to_csv'
app/controllers/registrations_controller.rb:139:in `block (2 levels) in find_by_registration_date'

app / controllers / registrations_controller.rb:137:在`find_by_registration_date'

编辑:这太奇怪了。如果我这样做:

  def find_by_registration_date
    @registrations = Registration.order :first_name 
    respond_to do |format|
      format.html
      format.csv { send_data @registrations.to_csv }
    end
  end

...然后按预期工作。我假设其中一个方法返回一个数组,另一个返回一个哈希值?

1 个答案:

答案 0 :(得分:1)

以下是我最终的结果...

应用程序/视图/注册/ find_by_registration_date.html.erb

<%= link_to 'Export CSV', csv_path(registration_date: @registration_date) %>

的routes.rb

  match 'csv' => 'registrations#export_csv', :as => :csv

应用程序/控制器/ registrations_controller.rb

  def export_csv
    @registration_date = params[:registration_date]
    @registrations = Registration.where("DATE(created_at) = ? ", @registration_date)
    csv = CSV.generate do |csv|
      csv << ["last_name", "id"]
       @registrations.each do |r|
         csv << [r.last_name, r.student_id]
       end
     end
     send_data(csv, :type => 'test/csv', :filename => 'add_hoc.csv')
  end

违背'瘦控制器/胖子模型'范例,但现在可以使用。