是否有相当于 ActiveRecord::Relation.update_all 的东西可以触发回调/观察者?
我想对 ActiveRecord 模型执行批量更新,大致如下:
MyModel.where(:field1=>"value1").update_all(:field1=>"value2")
我在 MyModel 上有一个观察者,我需要在此更新时触发它,但我没有看到这种情况发生。此行为与文档一致。
http://apidock.com/rails/ActiveRecord/Relation/update_all
是否有“除了迭代之外,还可以使用“内置”或“最佳实践”方式进行批量更新并触发观察者(例如):
MyModel.where(:field1=>"value1").each{ |m| m.update_attributes(: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") }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,没有这样的方法。原因可能是每个解决方案无论如何都必须在某个时刻进行迭代,因为每个对象上的所有回调都必须被调用。 “update_all”存在的原因是让开发人员能够直接使用 mysql API 调用批量更新记录(或多或少)......在某种意义上精确地规避任何 activerecord 功能,如验证和回调。
我希望这是您满意的答案。
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.