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?
ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.
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.
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.
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)
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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With