当您需要触发回调时如何更新所有内容?
假设我在名为 user_ids
的数组中有 15 个用户 ID。
比如说,如果我想将他们的所有名字更改为“Bob”,我可以这样做:
users = User.find(user_ids)
users.update_all( :name => 'Bob' )
不过,这不会触发回调。如果我需要触发这些记录保存的回调,据我所知,唯一的方法是使用:
users = User.find(user_ids)
users.each do |u|
u.name = 'Bob'
u.save
end
然而,这可能意味着控制器操作中的任务运行时间非常长。
所以,我的问题是,是否有其他更好/更高性能/更完善的方法来触发对一组记录的批量更新,确实触发记录上的回调?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不要使用each/find_each,而是尝试使用
update
方法:这只是以下内容的包装:
Instead of using each/find_each, try using
update
method instead:Which is just a wrapper for the following:
不,要运行回调,您必须实例化一个对象,这是昂贵的操作。我认为解决您的问题的唯一方法是将您在回调中执行的操作重构为单独的方法,该方法可以使用 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.
这是触发回调的另一种方式。 而不是使用
您可以使用的
不过,如果您要处理大量数据,我不会推荐这种方法, 方法。
希望有帮助!
Here's another way of triggering callbacks. Instead of using
you can use
I wouldn't recommend this approach if you're dealing with very large amounts of data, though.
Hope it helps!