How to touch multiple records in ActiveRecord?

I would like to update updated_at for several entries:

 users = User.in_mailing_list users.update_all(:updated_at => Time.now) 

Is there a shortcut for this purpose, say something like the users.touch_all method?

+8
ruby-on-rails activerecord
source share
4 answers

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 trigger N requests, rather than using update_all, which will do this in a single command.
+6
source share

You can do it as follows:

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

Note. Brackets are required, otherwise it tries to set updated_at and id instead of updating updated_at , where id is in user_ids

Hooray!

+4
source share

If you need ActibeRelaton touch ActibeRelaton , you must use the update_all method. It affects several records in one transaction:

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

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

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

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

+1
source share

This should do it:

 User.update(users, :updated_at => Time.now) 
0
source share

All Articles