Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 458
krunal shah Avatar asked Jun 28 '11 11:06

krunal shah


2 Answers

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)
like image 155
tokland Avatar answered Sep 24 '22 14:09

tokland


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

like image 35
Fernando Diaz Garrido Avatar answered Sep 24 '22 14:09

Fernando Diaz Garrido