How to convert array of ActiveRecord models to CSV?

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

    This might be off the original question but solve the problem. If you plan to make all or some of your Active Record models be able to convert to csv, you can use ActiveRecord concern. An example is shown below

    module Csvable
      extend ActiveSupport::Concern 
    
      class_methods do
        def to_csv(*attributes)
          CSV.generate(headers: true) do |csv| 
            csv << attributes 
    
            all.each do |record| 
              csv << attributes.map { |attr| record.send(attr) }
            end 
          end
        end
      end
    end
    

    The attribute provided will be used as the header for the CSV and it is expected that this attribute corresponds to methods name in the included class. Then you can include it in any ActiveRecord class of your choice, in this case, the User class

    class User 
      include Csvable 
    
    end
    

    Usage

    User.where(id: [1, 2, 4]).to_csv(:id, :name, :age)

    Note: This only works for ActiveRecord relation and not for arrays

    0 讨论(0)
  • 2020-12-23 14:22

    with julia_builder you can configure a csv export pretty easily.

    class UserCsv < Julia::Builder
      # specify column's header and value
      column 'Birthday', :dob
      # header equals 'Birthday' and the value will be on `user.dbo`
    
      # when header and value are the same, no need to duplicate it.
      column :name
      # header equals 'name', value will be `user.name`
    
      # when you need to do some extra work on the value you can pass a proc.
      column 'Full name', -> { "#{ name.capitalize } #{ last_name.capitalize }" }
    
      # or you can pass a block
      column 'Type' do |user|
        user.class.name
      end
    end
    

    and then

    users = User.all
    UserCsv.build(users)
    
    0 讨论(0)
提交回复
热议问题