gpt4 book ai didi

mysql - Rails 将两个不同的模型实例保存为单个事务

转载 作者:行者123 更新时间:2023-11-28 23:30:36 25 4
gpt4 key购买 nike

我正在为记录用户和公司模型数据的注册表单编写一个服务对象(仅供引用,我断然拒绝使用 nested_attributes)。

没有公司 (belongs_to) 的存在,用户就无法存在。

如果公司保存成功,用户保存不成功,如何回滚创建公司?

我在下面复制了测试来证明这一点..

  context 'when both are valid?' do
subject { -> { sign_up_object.save } }
it { should change(Company, :count).by(1) }
it { should change(sign_up_object, :company).to be_a Company }
it { should change(User, :count).by(1) }
it { should change(sign_up_object, :user).to be_a User }
end
context 'when COMPANY is invalid' do
subject { -> { sign_up_object.save } }
before { allow_any_instance_of(Company).to receive(:save!).and_return false }
it { should change(User, :count).by(0) }
it { should change(Company, :count).by(0) }
end
context 'when USER is invalid' do
before { allow_any_instance_of(User).to receive(:save!).and_return false }
subject { -> { sign_up_object.save } }
it { should change(User, :count).by(0) }
it { should change(Company, :count).by(0) } ->>>> this one fails!!!
end

我现在的代码看起来像这样

class SignUp

......

def save_resources
ActiveRecord::Base.transaction do
save_company
save_user
end
end

def save_company
company = new_company
self.company = company if company.save!
end

def save_user
user = new_user
self.user = user if user.save!
end
end

我确定 ActiveRecord::Base.transaction block 实际上没有做任何事情,因为我的测试显示用户规范是唯一失败的,因为公司数量正在增加1.

最佳答案

您可以在未创建用户时手动回滚事务:

举个例子:

class SignUp

......

def save_resources
ActiveRecord::Base.transaction do
save_company
save_user
raise ActiveRecord::Rollback if self.user.nil?
end
end

def save_company
company = new_company
self.company = company if company.save!
end

def save_user
user = new_user
self.user = user if user.save!
end
end

关于mysql - Rails 将两个不同的模型实例保存为单个事务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37436908/

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