rails - updating active record relation with multiple changed properties

半世苍凉 提交于 2019-12-25 09:38:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!