How to convert array of ActiveRecord models to CSV?

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

    One can also utilize the sql engine for this. E.g. for sqlite3:

    cat << EOF > lib/tasks/export-submissions.sql
    .mode      csv
    .separator ',' "\n"
    .header    on
    
    
    .once "submissions.csv"
    
    select
      *
    from submissions
    ;
    EOF
    
    sqlite3 -init lib/tasks/export-submissions.sql db/development.sqlite3 .exit
    

    If you are on CentOS 7 -- it ships with sqlite released in 2013. That version did not know separator and once yet. So you might need to download the latest binary from the web-site: https://sqlite.org/download.html install it locally, and use the full path to the local installation:

    ~/.local/bin/sqlite3 -init lib/tasks/export-submissions.sql db/development.sqlite3 .exit
    

提交回复
热议问题