Can I use update_all for an array?

I have a list of comments in one array. Can I use update_all for an array?

comments = Comments.find(:all,:conditions => ["test is not null"]) comments.update_all(:test => nil) 
+6
source share
2 answers

If you work with scopes ( find or all - in the old version of the Rails return array):

 comments = Comments.scoped(:conditions => "test IS NOT NULL") comments.update_all(:test => nil) 

In modern versions of Ruby / ActiveRecord, you can write:

 Comments.where.not(test: nil).update_all(test: nil) 
+9
source

update_all is a method provided by ActiveRecord, and you have Array, you have two options: use ActiveRecord through comments (update the database) or map the array, changing only objects in memory and not changing the database:

 comments = Comments.update_all({:test => nil}, 'test IS NOT NULL') 

or

 comments = Comments.find(:all,:conditions => ["test is not null"]) comments.map! { |c| c.test = nil unless c.test} 

EDIT: Error in second example, c.test not c

+3
source

Source: https://habr.com/ru/post/891545/


All Articles