Rails 3:为 after_create 回滚 [英] Rails 3: rollback for after_create
问题描述
我有一张报名表.
当用户注册时,应用程序应该将数据保存在 enrollments
表和 users
表中.(我需要这种分隔,因为用户的个人资料可以更改,但他为该特定注册输入的数据必须存档.因此,即使稍后用户更改了他的姓氏,我也会在注册表格中获得他的初始信息.)
When the user enrolls, the app is supposed to save the data in the enrollments
table and in the users
table. (I need this separation because the user's profile can change but the data he entered for that particular enrollment has to be archived. So even if later the user changes his last name, in the enrollment form I'll have his initial information.)
所以我正在考虑将数据保存在 enrollments
表中,然后进行 after_create 调用,就像这样...
So I was thinking about saving data in the enrollments
table then have a after_create call, like this...
class Enrollment < ActiveRecord::Base
after_create :save_corresponding_user
def save_corresponding_user
user = User.new
user.full_name = self.user_full_name
user.email = self.user_email
user.mobile_phone = self.user_mobile_phone
user.save
end
end
问题是,如果保存用户因任何原因失败怎么办.如何从 enrollments
表中回滚和销毁刚刚保存的数据?
The issue is, what if saving the user fails for any reason. How can I rollback and destroy the just saved data from the enrollments
table?
推荐答案
after_create 是保存当前模型的事务的一部分.因此,如果您的代码崩溃或 after_create 返回 false,它应该回滚当前事务并使 enrollment
保存无效.
after_create is a part of the transaction saving the current model. Therefore, if your code crashes or if after_create returns false, it should rollback the current transaction and invalidate the enrollment
saving.
如果你想模拟这个,把它添加到你的 after_create 中,看看是否一切都按预期工作:
If you want to simulate this, add this to your after_create and see if everything works as expected :
raise Exception.new("CRASH")
这篇关于Rails 3:为 after_create 回滚的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!