Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Faster save method?

I must convert ~ 1.300.000 records on my database. Do you know a method faster than this?

Article.find_each(&:save)
like image 319
brtsos Avatar asked Jun 29 '26 17:06

brtsos


2 Answers

If you're looking to update a single field in a table, you can use update_all on your ActiveRecord model.

Post.update_all(:published=>true)
# UPDATE "posts" SET "published" = 't'

This works with an ActiveRecord scopes as well.

Post.where(:published=>true).update_all(:published=>false) 
# SQL (3.3ms)  UPDATE "posts" SET "published" = 'f' WHERE "posts"."published" = 't'

By using this, you can use conditional statements (such as where) to pick out common rows in your table and perform update_all on them. This is assuming you want to do some form of attribute updating before saving the record.

like image 135
Damon Aw Avatar answered Jul 02 '26 07:07

Damon Aw


You can increase the number of records in batch (the default is 1000), this number depends on how much memory you have in your server:

Article.find_each(:batch_size => 5000) { |r| r.save }
like image 24
megas Avatar answered Jul 02 '26 07:07

megas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!