我如何'验证'在rails在rails [英] How do I 'validate' on destroy in rails

查看:137
本文介绍了我如何'验证'在rails在rails的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在破坏一个restful资源,我想保证几个事情,我允许destroy操作继续?基本上,我想要能够停止destroy操作,如果我注意到这样做会使数据库处于无效状态?在destroy操作上没有验证回调,那么如何验证是否应该接受destroy操作?

On destruction of a restful resource, I want to guarantee a few things before I allow a destroy operation to continue? Basically, I want the ability to stop the destroy operation if I note that doing so would place the database in a invalid state? There are no validation callbacks on a destroy operation, so how does one "validate" whether a destroy operation should be accepted?

推荐答案

你可以提出一个异常,然后你抓住。

You can raise an exception which you then catch. Rails wraps deletes in a transaction, which helps matters.

例如:

class Booking < ActiveRecord::Base
  has_many   :booking_payments
  ....
  def destroy
    raise "Cannot delete booking with payments" unless booking_payments.count == 0
    # ... ok, go ahead and destroy
    super
  end
end

或者,您可以使用before_destroy回调。此回调通常用于销毁依赖记录,但您可以抛出异常或添加错误。

Alternatively you can use the before_destroy callback. This callback is normally used to destroy dependent records, but you can throw an exception or add an error instead.

def before_destroy
  return true if booking_payments.count == 0
  errors.add :base, "Cannot delete booking with payments"
  # or errors.add_to_base in Rails 2
  false
end

myBooking.destroy myBooking.errors 将在返回时填充。

这篇关于我如何'验证'在rails在rails的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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