0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

ruby(rails)でデータ量が多い時でもcsvファイルを比較的速く作成する書き方

Last updated at Posted at 2020-02-17

メモなので分かりにくいかもです

user_data_csv = CSV.generate do |csv|
  csv_column_names = ["名前", "年齢"]
  csv << csv_column_names
  
  User.all.find_each do |user|
    csv << [user.name, user.age]
  end
end

File.open("all_user_data.csv", "w") do |csv| 
  csv.puts user_data_csv
end

データをまとめてからcsvファイルに書き出してるので、こう書くより速い

CSV.open('all_user_data.csv','w') do |csv|
  csv_column_names = ["名前", "年齢"]
  csv << csv_column_names
  
  User.all.find_each do |user|
    csv << [user.name, user.age]
  end
end

こちらにさらにいいやり方が載っていました。
https://www.techscore.com/blog/2017/12/04/fast_and_low-load_processing_method_when_exporting_csv_from_db_with_rails/

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?