如何更新所有当你需要回调解雇? [英] How to update all when you need callbacks fired?

查看:160
本文介绍了如何更新所有当你需要回调解雇?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我有15个用户的ID在称为数组 user_ids

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.

所以,我的问题是,有没有其他的更好/更高性能/ railsier的方式来触发一个批量更新一组记录中的没有的触发回调的记录?

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆