In Rails Console. how to update a field for all records?
Notification.update_all(email: true)
is the basic answer.
You don't have to "loop through" per se by writing your own block: you can let active record do the hard work for you - here is an example of where you have an array of ids and you want to update their emails (i basically took this example straight from one of my controllers):
@notifications = Notification.where(id: [1,2,3,4,5,6]).update_all(email: true)
Edit: folks watch out for sql injection do not include a params[:notification_ids]
in your "where" method with a raw string, without escaping, or you will suffer sql injection attacks; or be safe and use a hash. If that doesn't make sense, please review the following: https://guides.rubyonrails.org/security.html#sql-injection
You're looking for update_all
. See doc.
Beware, no callbacks are triggered this way.
You can use:
Notification.update_all(email: true)
If you additionally have a condition while updating you should use:
Notification.find_each { |n| n.email = (n.id > 100) ? true : false }
Use Something.all
is bad idea for huge db table.
this should work
Notification.all.each do |n| n.update_attribute(:email, true); end
edit: made custom from bricker:
Notification.all.each { |n| n.update_attribute(:email, true) }