如何在需要触发回调时更新所有内容? [英] How to update all when you need callbacks fired?
问题描述
假设我在名为 user_ids
的数组中有 15 个用户 ID.
Let's say I've got 15 user ids in an array called 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 does trigger the callbacks on the records?
推荐答案
不,要运行回调,您必须实例化一个对象,这是一项开销很大的操作.我认为解决您的问题的唯一方法是将您在回调中执行的操作重构为单独的方法,该方法可以使用 select_all 方法检索的数据而无需对象实例化.
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.
这篇关于如何在需要触发回调时更新所有内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!