Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4 update_all and set value from another field

I need to do some bulk updates in some models and set value of a field as value of another field.

Right now I can do that with raw sql like this:

ActiveRecord::Base.connection.execute("UPDATE `deleted_contents` SET `deleted_contents`.`original_id` = `deleted_contents`.`id` WHERE `deleted_contents`.`original_id` is NULL")

This is working fine, however I need to do this using ActiveRecord query interface due to many reasons. I tried:

DeletedContent.where(original_id: nil).update_all(original_id: value_of_id_column)

For value_of_id_column I tried :id, self.id, id, etc, nothing works. What should I set for value_of_id_column to get the original query generated by rails? Is this possible, or using the raw sql is the only solution?

Also I do not want to iterate over each record and update. This is not a valid solution for me:

DeletedContent.where(original_id: nil).each do |deleted_content|
    update_each_record
end
like image 726
Eduard Avatar asked Aug 08 '15 10:08

Eduard


1 Answers

I'm pretty sure you cannot obtain that query by passing a hash to update_all.

The closest to what you want to obtain would be:

DeletedContent.where(original_id: nil).update_all("original_id = id")
like image 132
Sebastian Zaha Avatar answered Sep 21 '22 04:09

Sebastian Zaha