[Ruby] How to update with activerecord-import

less than 1 minute read

I didn’t write it subtly, so I made a note for myself

update_users = []
users.each do |user|
  user.name = "John"
  user.email = "[email protected]"
  update_users << user
end

#Here on_duplicate_key_Pass the column name you want to update to update
User.import update_users, on_duplicate_key_update: [:name, :email]

I understand that the default of Gem is to perform INSERT, and by specifying the column name with the ʻon_duplicate_key_update` option, the specified column will be updated (Upsert) when the key is covered.

So if you update only the original user and pass it, it will only be updated.

By the way, it seems that the method of specifying this option differs depending on the 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]}