in rails, how to return records as a csv file

后端 未结 10 1231
醉话见心
醉话见心 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:39

    If you're simply wanting to get the csv database yourself from the console you can do so in a few lines

    tags = [Model.column_names]
    rows = tags + Model.all.map(&:attributes).map(&:to_a).map { |m| m.inject([]) { |data, pair| data << pair.last } }
    File.open("ss.csv", "w") {|f| f.write(rows.inject([]) { |csv, row|  csv << CSV.generate_line(row) }.join(""))}
    

提交回复
热议问题