Best practice updating a single attribute across multiple records

I am writing an exporter in my current Rails3 project right now. This exporter should mark each exported record as "exported" (bool). I know how to do this easily in a loop, but to be honest, it’s not very convenient to let Rails query a database, say 300 times in a row, just set one field for 300 records.

Does anyone know if there is a good way to optimize this? Should I play manually with prepared statements, or will Rails3 take care of this automatically? Is there another SQL command to do this in one step or something else?

thanks for the help

  • Arne
+5
source share
2 answers

Use the method update_allfor the class. From the Rails API :

# Update all books with 'Rails' in their title
Book.update_all "author = 'David'", "title LIKE '%Rails%'"
+15
source

Because ActiveRecord 4.0 is deprecated in this way ( Rails API ), the current way to do the same is:

# Update all books with 'Rails' in their title
Book.where('title LIKE ?', '%Rails%').update_all(author: 'David')
+5
source

All Articles