因此,假设您有2个模型,人员和地址,并且每个人只有一个地址可以标记为“主要”。因此,如果我想更改一个人的主要地址,则需要使用一笔交易,将新地址标记为主要地址,而不标记旧地址。据我所知,在控制器中使用事务并不好,所以我在模型中有一种特殊的方法,那就是我所拥有的:
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?
我可能可以将该事务放入控制器中,并在急救部件中呈现该错误消息,但是我想它是不正确的,或者我可以将该方法放入回调中,但是想象有某种原因我不能做到这一点,还有什么办法?
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句