4
2

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.

activerecord-importでUpdateする方法

Last updated at Posted at 2020-08-05

微妙に書いてなかったので自分用にメモ

update_users = []
users.each do |user|
  user.name = "John"
  user.email = "test@mail.com"
  update_users << user
end

# ここのon_duplicate_key_updateに更新したい列名を渡す
User.import update_users, on_duplicate_key_update: [:name, :email]

GemのデフォルトはINSERTをする用途でon_duplicate_key_updateオプションで列名を指定してあげることでキーが被ったときに指定した列が更新される(Upsertされる)という理解をした。

なので元々あるユーザーだけを更新して渡せばUpdateだけされるという感じ。

ちなみにDBによってこのオプションの指定の仕方は違うらしい
https://github.com/zdennis/activerecord-import/#duplicate-key-update

# MySQL version
Book.import [book], on_duplicate_key_update: [:title]

# PostgreSQL version
Book.import [book], on_duplicate_key_update: {conflict_target: [:id], columns: [:title]}
4
2
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
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?