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)
You cannot use update_all
with arrays, only with scopes. find
or all
(in older version of Rails) return an array. Instead:
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)
update_all is a method provided by ActiveRecord, and what you have is an Array, you have two options either use ActiveRecord through Comments (will update database) or map the array, changing only the objets in memory and not modifying 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 the second example, is c.test not c
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