How to convert array of ActiveRecord models to CSV?

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

    Yet another similar answer, but here's what I usually do.

    class ApplicationRecord < ActiveRecord::Base
      self.abstract_class = true
    
      def self.to_csv
        CSV.generate do |csv|
          csv << column_names
          all.find_each do |model|
            csv << model.attributes.values_at(*column_names)
          end
        end
      end
    end
    

    Instead of hacking existing module, I'd usually put this code in the ApplicationRecord class, the base class of all the models (usually).

    If any further elaboration is needed, I'd add a named parameter to the to_csv method, and handle those features as much as possible in this class.

    This way, the to_csv method will be available to both Model and its Relation. E.g.

    User.where(role: :customer).to_csv
    # => gets the csv string of user whose role is :customer
    

提交回复
热议问题