Ruby-on-rails `after_create` 和 `after_save` 之间有什么区别以及何时使用哪个?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6422199/
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
What is the difference between `after_create` and `after_save` and when to use which?
提问by Swapnil Chincholkar
Are after_createand after_savethe same as per functionality?
是after_create和after_save同为每个功能?
I want to do an operation with the email of a user after its account creation.
我想在创建帐户后对用户的电子邮件进行操作。
I want to do that operation when it is saved in the database.
我想在将其保存在数据库中时执行该操作。
which is preferable to use: after_createor after_save?
哪个更适合使用: after_create或after_save?
回答by Taryn East
after_createonly works once - just after the record is first created.
after_create只工作一次 - 就在第一次创建记录之后。
after_saveworks every time you save the object - even if you're just updating it many years later
after_save每次保存对象时都有效 - 即使您在多年后才更新它
So if you want to do this email operation only just the once (and then never again) then use after_create.
因此,如果您只想执行此电子邮件操作一次(然后再也不执行),请使用after_create.
If you want to do it everytime the object is saved, then do it in after_save
如果你想每次保存对象时都这样做,那么在after_save
回答by Michael Kohl
回答by pensebien
after_save()
Works fine when you have to save models that do not save very often. For this particular example of changing records frequently it would be advisable to use
当您必须保存不经常保存的模型时,效果很好。对于这个频繁更改记录的特定示例,建议使用
after_commit()
make sure that the model is saved in the database before the action is executed after_commit :calculate_credit_score
确保在执行操作之前将模型保存在数据库中 after_commit :calculate_credit_score
def calculate_credit_score
#Call a Cron job
end

