Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to touch multiple records in ActiveRecord?

I'd like to update the updated_at for a few records:

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

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

like image 308
ohho Avatar asked Oct 18 '13 10:10

ohho


People also ask

What does ActiveRecord base do?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.

Is ActiveRecord a framework?

1.3 Active Record as an ORM Framework Represent inheritance hierarchies through related models. Validate models before they get persisted to the database. Perform database operations in an object-oriented fashion.

What is an ActiveRecord relation object?

The Relation Class. Having queries return an ActiveRecord::Relation object allows us to chain queries together and this Relation class is at the heart of the new query syntax. Let's take a look at this class by searching through the ActiveRecord source code for a file called relation.


3 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 cause N requests as opposed to using update_all which would do it in a single command.
like image 197
NikoRoberts Avatar answered Oct 03 '22 19:10

NikoRoberts


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!

like image 26
Luke Avatar answered Oct 03 '22 17:10

Luke


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

like image 38
Oleh Sobchuk Avatar answered Oct 03 '22 18:10

Oleh Sobchuk