如何挽救模型交易并向用户显示错误? [英] How to rescue model transaction and show the user an error?

查看:62
本文介绍了如何挽救模型交易并向用户显示错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,假设您有2个模型,人员和地址,而每个人只有一个地址可以标记为主要。因此,如果我想更改某人的主要地址,则需要使用一笔交易,将新地址标记为主要地址,而不标记旧地址。据我所知,在控制器中使用事务不是很好,所以我在模型中有一种特殊的方法,那就是我得到的:

So imagine you have 2 models, Person and Address, and only one address per person can be marked as 'Main'. So if I wanna change a person's main address, I need to use a transaction, to mark the new one as main and unmark the old one. And as far as I know using transactions in controllers is not good so I have a special method in model, thats what I've got:

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?

So thequestion is, if the transaction in the model method fails, I need to rescue it and notify the user about the error, how do I do that? Is there a way to make this model method return true or false depending on whether the transaction was successful or not, like save method does?

我可能可以将该交易放入控制器并在急救部件中呈现错误消息,但是我想它是不正确的,或者我可以将该方法放在回调中,但是可以想象有某种原因我不能做到这一点,还有什么选择呢?

I probably could put that transaction in the controller and render the error message in the rescue part, but I guess its not right or I could put that method in a callback, but imagine there is some reason why I cant do that, whats the alternative?

PS不注意查找具有参数id和id2的实例,只是随机的事情来表明我有2个实例

PS dont pay attention to finding instances with params id and id2, just random thing to show that I have 2 instances

推荐答案

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, an exception looks like:

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

并且:

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

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

如果要保留活动模型错误的替代解决方案:

Alternate solution if you want to keep your active model errors:

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

这篇关于如何挽救模型交易并向用户显示错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆