问题
I have an active record relation defined like this:
contacts = Contact.where("status = 'waiting'")
I then run an .each loop and change properties of contacts depending on some logic.
I don't want to do a save! on each individual contact... how can I better save the entire contacts relation after the loop?
contacts.each do |contact|
//Change properties of contact here
end
How do I save the newly updates contacts activerecord relation after it contains its new properties?
The most efficient way can't be doing a contact by contact save.
回答1:
update_all saves you from doing the loop and do the save for you, here is the documentation. https://apidock.com/rails/v4.0.2/ActiveRecord/Relation/update_all
回答2:
You could use activerecord-import. As you said, you could assign all the new values for each contacts and finally save the changes in a bulk manner with this upsert.
来源:https://stackoverflow.com/questions/45363743/rails-updating-active-record-relation-with-multiple-changed-properties