krunal shah krunal shah - 3 months ago 7
Ruby Question

Can I use update_all on array?

I have list of comments in one array. Can I use update_all on array ?

comments = Comments.find(:all,:conditions => ["test is not null"])

comments.update_all(:test => nil)

Answer

You can if you work with scopes (find or all -in older version of Rails- returned an array):

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

On modern versions of Ruby/ActiveRecord you can write:

Comments.where.not(test: nil).update_all(test: nil)
Comments