gpt4 book ai didi

ruby-on-rails - 如何挽救模型交易并向用户显示错误?

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

假设您有 2 个模型,Person 和 Address,每个人只能将一个地址标记为“主要”。所以如果我想改变一个人的主要地址,我需要使用交易,将新地址标记为主要地址并取消标记旧地址。据我所知,在 Controller 中使用事务并不好,所以我在模型中有一个特殊的方法,这就是我所拥有的:

AddressesController < ApplicationController
def update
@new_address = Address.find(params[:id])
@old_address = Address.find(params[:id2])
@new_address.exchange_status_with(@old_address)
end
end

型号:

class Address < ActiveRecord::Base
def exchange_status_with(address)
ActiveRecord::Base.transaction do
self.save!
address.save!
end
end
end

所以问题是,如果模型方法中的事务失败了,我需要拯救它并通知用户错误,我该怎么做?有没有办法让这个模型方法根据交易是否成功返回 true 或 false,就像 save 方法一样?

我可能可以将该事务放在 Controller 中并在救援部分呈现错误消息,但我猜这是不对的,或者我可以将该方法放在回调中,但想象一下我不能这样做的某些原因,还有什么选择?

PS 不要注意查找具有参数 id 和 id2 的实例,只是随机显示我有 2 个实例

最佳答案

def exchange_status_with(address)
ActiveRecord::Base.transaction do
self.save!
address.save!
end
rescue ActiveRecord::RecordInvalid => exception
# do something with exception here
end

仅供引用,异常看起来像:

#<ActiveRecord::RecordInvalid: Validation failed: Email can't be blank>

和:

exception.message
# => "Validation failed: Email can't be blank"

旁注,您可以将 self.save! 更改为 save!


如果您想保留事件模型错误的替代解决方案:

class MyCustomErrorClass < StandardError; end

def exchange_status_with(address)
ActiveRecord::Base.transaction do
raise MyCustomErrorClass unless self.save
raise MyCustomErrorClass unless address.save
end
rescue MyCustomErrorClass
# here you have to check self.errors OR address.errors
end

关于ruby-on-rails - 如何挽救模型交易并向用户显示错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24218477/

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