13
13

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 5 years have passed since last update.

railsでcsvを読み込んで、DBへ保存する

Last updated at Posted at 2018-04-04

##csv

user_data.csv
id,name,email,created_at,updated_at
1,user1,example.com,2018-02-17 00:00:00,2018-02-17 00:00:00
2,user2,example.com,2018-02-17 00:00:00,2018-02-17 00:00:00
3,user3,example.com,2018-02-17 00:00:00,2018-02-17 00:00:00
4,user4,example.com,2018-02-17 00:00:00,2018-02-17 00:00:00

##ruby

import.rb
require 'csv'

CSV.read("user_data.csv", headers: true).each do |row|
  user = User.create!(
    id: row['id'],
    name: row['name'],
    email: row['email'],
    created_at: row['created_at'],
    updated_at: row['updated_at']
  )
end

###実行!

$ rails runner import.rb

## 問題
N+1になってしまうので数が多い場合は、sequelactiverecord-importなどのgemを使ってbulkinsertする

13
13
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
13
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?