Rails 3. before_destroy验证以防止删除父记录

leo*_*nel 8 ruby ruby-on-rails ruby-on-rails-3

我有货物和发票.

发票属于装运
货物有一张发票

如果货件确实有发票,则无法删除货件.我需要在模型中设置它,因为我正在使用ActiveAdmin.

所以我在shipping.rb中这样做了

has_one :invoice
before_destroy :check_for_invoice

private

def check_for_invoice
  unless invoice.nil?
    self.errors[:base] << "Cannot delete shipment while its invoice exists."
  end
end
Run Code Online (Sandbox Code Playgroud)

但我只是收到一条黄色信息,上面写着"无法删除货件"但实际上已将其删除.

如何防止货件被删除?

Pau*_*son 23

before_destroy回调需要一个真/假值,以确定是否要proceeed.

添加一个return falsecheck_for_invoice喜欢的:

has_one :invoice
before_destroy :check_for_invoice

private

def check_for_invoice   
  unless invoice.nil?     
    self.errors[:base] << "Cannot delete shipment while its invoice exists."
    return false   
  end 
end 
Run Code Online (Sandbox Code Playgroud)


小智 5

我的2美分发货.rb

has_one :invoice, dependent: :restrict
Run Code Online (Sandbox Code Playgroud)

我认为它会起作用,我在另一个线程中看到了这个解决方案.我现在正在尝试我的模特.