Ruby-on-rails 如何在需要触发回调时更新所有内容?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6931812/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to update all when you need callbacks fired?
提问by Andrew
Let's say I've got 15 user ids in an array called user_ids.
假设我在名为 的数组中有 15 个用户 ID user_ids。
If I want to, say, change all of their names to "Bob" I could do:
如果我想,比如说,把他们所有的名字都改成“鲍勃”,我可以这样做:
users = User.find(user_ids)
users.update_all( :name => 'Bob' )
This doesn't trigger callbacks, though. If I need to trigger callbacks on these records saving, to my knowledge the only way is to use:
但是,这不会触发回调。如果我需要在保存这些记录时触发回调,据我所知,唯一的方法是使用:
users = User.find(user_ids)
users.each do |u|
u.name = 'Bob'
u.save
end
This potentially means a very long running task in a controller action, however.
然而,这可能意味着控制器操作中的一个非常长时间运行的任务。
So, my question is, is there any other better / higher performance / railsier way to trigger a batch update to a set of records that doestrigger the callbacks on the records?
所以,我的问题是,是否有其他更好/更高性能/更流畅的方式来触发对一组记录的批量更新,从而触发记录上的回调?
采纳答案by iafonov
No, to run callbacks you have to instantiate an object which is expensive operation. I think the only way to solve your problem is to refactor actions that you're doing in callback into separate method that could use data retrieved by select_all method without object instantiation.
不,要运行回调,您必须实例化一个代价高昂的对象。我认为解决您的问题的唯一方法是将您在回调中执行的操作重构为单独的方法,该方法可以使用 select_all 方法检索的数据而无需对象实例化。
回答by untitled
Instead of using each/find_each, try using updatemethod instead:
不要使用 each/find_each,update而是尝试使用方法:
models.update(column: value)
回答by maxhm10
Here's another way of triggering callbacks. Instead of using
这是触发回调的另一种方式。而不是使用
models.update_all(params)
you can use
您可以使用
models.find_each { |m| m.update_attributes(params) }
I wouldn't recommend this approach if you're dealing with very large amounts of data, though.
Hope it helps!
不过,如果您要处理非常大量的数据,我不会推荐这种方法。
希望能帮助到你!

