如果父记录有子记录,如何防止删除父记录? [英] How do I prevent deletion of parent if it has child records?

查看:30
本文介绍了如果父记录有子记录,如何防止删除父记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经浏览了 Ruby on Rails 指南,但我似乎无法弄清楚如何防止某人删除具有子项的父记录.例如.如果我的数据库有 CUSTOMERS 并且每个客户可以有多个 ORDERS,我想防止有人删除数据库中有任何订单的客户.他们应该只能删除没有订单的客户.

I have looked through the Ruby on Rails guides and I can't seem to figure out how to prevent someone from deleting a Parent record if it has Children. For example. If my database has CUSTOMERS and each customer can have multiple ORDERS, I want to prevent someone from deleting a customer if it has any orders in the database. They should only be able to delete a customer if it has no orders.

在定义模型之间的关联时有没有办法强制执行此行为?

Is there a way when defining the association between models to enforce this behavior?

推荐答案

您可以在回调中执行此操作:

You could do this in a callback:

class Customer < ActiveRecord::Base
  has_many :orders
  before_destroy :check_for_orders

  private

  def check_for_orders
    if orders.count > 0
      errors.add_to_base("cannot delete customer while orders exist")
      return false
    end
  end
end

编辑

请参阅此答案以获得更好的方法.

see this answer for a better way to do this.

这篇关于如果父记录有子记录,如何防止删除父记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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