arnekolja
arnekolja

Reputation: 1687

Best practise for updating single attribute on multiple records

I am writing an exporter within my current Rails3 project right now. This exporter has to mark every exported record as "exported" (bool). I know how to do this easily in a loop, but honestly, it doesn't feel very good to let Rails query the database, say, 300 times in a row, just to set one field on 300 records.

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

Thanks for your help

Upvotes: 7

Views: 5297

Answers (2)

Redithion
Redithion

Reputation: 1016

Since ActiveRecord 4.0 that way is deprecated (Rails API), current way of doing the same is:

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

Upvotes: 10

Voldy
Voldy

Reputation: 12868

Use update_all method on Class. From Rails API:

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

Upvotes: 15

Related Questions