Have you ever found that you needed to update more than one record at a time? Rails has an elegant solution for this:
Updates all records in the current relation with details given. This method constructs a single SQL UPDATE statement and sends it straight to the database. It does not instantiate the involved models and it does not trigger Active Record callbacks or validations. However, values passed to update_all will still go through Active Record’s normal type casting and serialization.
Say you are working with a library book tracking system. One user has returned three books today.
# user with id 100 checked out books: User.find(100).books.checked_out > [ #<Book id:1, title: 'The Hobbit', status: 'checked_out', user_id: 100>, #<Book id:2, title: 'Children of Time', status: 'checked_out', user_id: 100>, #<Book id:3, title: 'The Count of Monte Cristo', status: 'checked_out', user_id: 100> ]
You could update each record individually using the commonly used
update active record function, however rails also provides the
checked_out_books = User.find(100).books.checked_out checked_out_books.update_all(status: 'returned')
Which is great! We have successfully marked the books in the system as
returned with one call to the database (instead of 3)!
Some things to consider when using this method:
- this method does not trigger model callbacks
- this method does not update the
updated_atfield automatically. However you can manually pass the current