in rails, how to return records as a csv file

后端 未结 10 1247
醉话见心
醉话见心 2020-11-28 05:02

I have a simple database table called \"Entries\":

class CreateEntries < ActiveRecord::Migration
  def self.up
    create_table :entries do |t|
      t.st         


        
10条回答
  •  孤街浪徒
    2020-11-28 05:20

    Take a look into the FasterCSV gem.

    If all you need is excel support, you might also look into generating a xls directly. (See Spreadsheet::Excel)

    gem install fastercsv
    gem install spreadsheet-excel
    

    I find these options good for opening the csv file in Windows Excel:

    FasterCSV.generate(:col_sep => ";", :row_sep => "\r\n") { |csv| ... }
    

    As for the ActiveRecord part, something like this would do:

    CSV_FIELDS = %w[ title created_at etc ]
    FasterCSV.generate do |csv|
      Entry.all.map { |r| CSV_FIELDS.map { |m| r.send m }  }.each { |row| csv << row }
    end
    

提交回复
热议问题