LoginSignup
0
0

More than 1 year has passed since last update.

RailsのMongoidのモデルをCSVに出力する

Posted at

以下のコードの変数modelsに出力したいモデルを設定して保存します。
rails runnerで第1引数に出力先ディレクトリを設定して実行してください。

# CSVに出力したいモデルを指定してください
models = [Model1, Model2, Model3]

# スクリプト実行時、第1引数に出力先ディレクトリを指定してください
dir = ARGV[0]

models.each do |model|
  file = "#{model.to_s.pluralize.underscore}.csv"

  CSV.open(File.join(dir, file), "wb") do |csv|
    fields = model.fields.map {|f| f[0]}.sort
    csv << fields

    model.each do |row|
      values = fields.map {|f| row[f]}
      csv << values
    end
  end
end

環境

動作確認に使用した環境は以下の通りです。

App バージョン
Ruby 2.6.6
Rails 6.1.4
Mongoid 7.3.3
0
0
0

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