Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Rails Console. how to update a field for all records?

how can I update a table Notification.email to all true in console?

In console, I'd like to loop through all the records in the table and set email = true.

Ideas?

like image 946
AnApprentice Avatar asked Oct 07 '11 21:10

AnApprentice


3 Answers

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) }
like image 107
cbron Avatar answered Nov 14 '22 13:11

cbron


You're looking for update_all. See doc.

Beware, no callbacks are triggered this way.

like image 34
apneadiving Avatar answered Nov 14 '22 13:11

apneadiving


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.

like image 14
m.seliverstov Avatar answered Nov 14 '22 13:11

m.seliverstov