How to convert array of ActiveRecord models to CSV?

后端 未结 8 1503
情话喂你
情话喂你 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:08

    If you need something quick and dirty, not so much for production as just grabbing some data for a non-technical user, you could paste this in console:

    require 'csv'
    class ActiveRecord::Relation
      def to_csv
        ::CSV.generate do |csv|
          csv << self.model.attribute_names
          self.each do |record|
            csv << record.attributes.values
          end
        end
      end
    end
    

    Then do: User.select(:id,:name).all.to_csv

    If you were going to production, I'd probably turn this into a decorator around ActiveRecord::Relation and more precisely ensuring that the order of your fields/attributes.

提交回复
热议问题