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 1 year has passed since last update.

【Ruby】RubyでCSVファイルのデータを登録する方法

Last updated at Posted at 2023-02-26

どんなときに使えるか

Rails consoleを使用して、production環境やstaging環境でcsvファイルのデータをDBに登録したいときに使える。

csvファイルのデータを登録する方法 <実際のコード>

DATA_PATH = "/data/tmp/"
FILE_NAME = "goriragorira.csv"

CSV.foreach("#{DATA_PATH}#{FILE_NAME}", headers: true, return_headers: false) do |row|
  begin
    ActiveRecord::Base.transaction do
      @gorira = Gorira.new(
        name: row['name'],
        gorira_seikaku_text: row['gorira_seikaku_text']
      )
      @gorira.save!
    end
  rescue Exception => error
    Rails.logger.error(error)
  end
end

haeders: true
これは、csvファイルの1行目がヘッダーとして認識されるため、データの登録はされない。要するに無視される。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?