How to convert array of ActiveRecord models to CSV?

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

    The following will write the attributes of all users to a file:

    CSV.open("path/to/file.csv", "wb") do |csv|
      csv << User.attribute_names
      User.find_each do |user|
        csv << user.attributes.values
      end
    end
    

    Similarly you could create a CSV string:

    csv_string = CSV.generate do |csv|
      csv << User.attribute_names
      User.find_each do |user|
        csv << user.attributes.values
      end
    end
    

提交回复
热议问题