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

所以想象你有两个模型,人和地址,每个人只能有一个地址被标记为“主”.所以如果我想改变一个人的主要地址,我需要使用一个交易,将新的一个标记为主,并取消标记旧的.据我所知,在控制器中使用交易不是很好,所以我在模型中有一个特殊的方法,这就是我所得到的:
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方法

我可能会将该事务放在控制器中,并在救援部分中显示错误消息,但是我猜测它不正确,或者我可以将该方法放在回调中,但是想象一下,为什么我不能这样做,什么是替代?

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

FYI,一个例外情况如下:

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

和:

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

旁注,你可以改变自我!保存!

如果您想要保持主动型号错误,请选择其他解决方案:

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

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...