gpt4 book ai didi

ruby-on-rails - rails 3 : rollback for after_create

转载 作者:数据小太阳 更新时间:2023-10-29 06:55:52 27 4
gpt4 key购买 nike

我有一张报名表。

当用户注册时,应用程序应该将数据保存在 enrollments 表和 users 表中。 (我需要这种分离,因为用户的个人资料可以更改,但他为该特定注册输入的数据必须存档。因此,即使以后用户更改了他的姓氏,在注册表格中我也会有他的初始信息。)

所以我正在考虑将数据保存在 enrollments 表中,然后进行 after_create 调用,就像这样...

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 表中刚刚保存的数据?

最佳答案

after_create 返回 false 将不执行任何操作。

The whole callback chain is wrapped in a transaction. If any before callback method returns exactly false or raises an exception, the execution chain gets halted and a ROLLBACK is issued; after callbacks can only accomplish that by raising an exception.

此外,您必须引发 ActiveRecord::Rollback:

Any exception that is not ActiveRecord::Rollback will be re-raised by Rails after the callback chain is halted. Raising an exception other than ActiveRecord::Rollback may break code that does not expect methods like save and update_attributes (which normally try to return true or false) to raise an exception.

http://guides.rubyonrails.org/active_record_callbacks.html#halting-execution

我做这样的事情:

after_create do
if condition
errors.add(:attr, 'Blah blah blah.')
raise ActiveRecord::Rollback
end
end

对于 Rails 3:http://guides.rubyonrails.org/v3.2.13/active_record_validations_callbacks.html#halting-execution

关于ruby-on-rails - rails 3 : rollback for after_create,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11692363/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com