开发者

Is there an equivalent of ActiveRecord::Relation.update_all that triggers callbacks/observers?

开发者 https://www.devze.com 2023-04-12 18:38 出处:网络
I want to perform a bulk update of ActiveRecord models, along the lines of: MyModel.where(:field1=>\"value1\").update_all(:field1=>\"value2\")

I want to perform a bulk update of ActiveRecord models, along the lines of:

MyModel.where(:field1=>"value1").update_all(:field1=>"value2")

I've got an Observer on MyModel that I need to be triggered on this update, and I don't see that happening. This behavior agrees with the docs.

http://apidock.com/rails/ActiveRecord/Relation/update_all

Is there开发者_开发技巧 a "built-in" or "best-practice" way to do a bulk update and trigger observers, other than iterating (e.g.):

MyModel.where(:field1=>"value1").each{ |m| m.update_attributes(:field1=>"value2") }


No there is no such way. The reason is probably that every solution would have to iterate at some point anyhow, because all the callbacks on each object would have to be called. The reason why 'update_all' exists, is to give developers the possibility to bulk update records (more or less) directly with mysql API calls ... in a sense to precisely circumwent any activerecord functionality like validations and callbacks.

I hope this is a satisfying answer for you.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号