How to touch multiple records in ActiveRecord?

You can do it like this:

User.update_all({updated_at: Time.now}, {id: user_ids})

Note: The braces are required, otherwise it tries to set updated_at and id, instead of updating updated_at where id is in user_ids

Cheers!


Not sure if rhernando's answer works in older versions of Ruby, but this is a much clearer method in my opinion and works in Ruby 2+

users.each(&:touch)
  • NB. As mentioned in the comments this will cause N requests as opposed to using update_all which would do it in a single command.

If you need touch ActiveRelaton records you have to use update_all method. It touches multiple records in a single transaction:

User.update_all(updated_at: Time.current)
User.where(active: true).update_all(active: false)

But if you have Array of records, in this case, you use only each with update

users.each { |user| user.update(active: true) }

the disadvantage of this case: for each user will be a separate transaction