ActiveRecordでbulk insert とupdateしたい
解決
insert
Book.insert_all([
{ id: 1, title: "Rework", author: "David" },
{ id: 1, title: "Eloquent Ruby", author: "Russ" }
])
created_at, updated_atは自動付与されないことに気をつける(DBの設定が自動挿入になっていればOK)
Upcoming Rails 6 Bulk insert/Upsert feature - Josef Šimánek - Medium で紹介のあるActiveRecord::Persistence::ClassMethods - insert_all
update_all
# Update all books with 'Rails' in their title
Book.where('title LIKE ?', '%Rails%').update_all(author: 'David')
Note
ポイントの加算などを一括で行いたい場合は、下記のように設定できる
Point.where(user_id: [1, 2]).update_all("point = point + 100")
update_all (ActiveRecord::Relation) - APIdock
Note
How to convert ActiveRecord results into an array of hashes - Stack Overflow より、serializable_hash
を使用して、ModelインスタンスからHashを作成を試みたが、下記の挙動により断念。
- enumが文字列
- created_at, update_at がnil