How to convert array of ActiveRecord models to CSV?

后端 未结 8 1505
情话喂你
情话喂你 2020-12-23 13:34

I got an array of ActiveRecord models that I wish to convert to a CSV. I tried researching gems like FasterCSV, but they just seem to work with strings and arrays, not Activ

8条回答
  •  轮回少年
    2020-12-23 14:15

    I had this same problem and combined a couple of these answers so I could call to_csv on a model or relation, then input a file name and create a csv file.

    class ApplicationRecord < ActiveRecord::Base
      self.abstract_class = true
    
      def self.to_csv
        require 'csv'
    
        p "What is the name of your file? (don't forget .csv at the end)"
    
        file_name = gets.chomp
    
        CSV.open("#{file_name}", "wb") do |csv|
          csv << column_names
          all.find_each do |model|
            csv << model.attributes.values_at(*column_names)
          end
        end
      end
    end
    

    Now from console you can call .to_csv on any model or any db query or activerecord relation.

提交回复
热议问题