How to convert array of ActiveRecord models to CSV?

后端 未结 8 1507
情话喂你
情话喂你 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条回答
  •  Happy的楠姐
    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)
    

提交回复
热议问题