且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如果父记录有子记录,如何防止删除父记录?

更新时间:2023-12-01 18:08:52

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

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.