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

时间:2012-01-11 19:23:01

标签: ruby-on-rails ruby 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

但我只是收到一条黄色信息,说“发货无法删除”,但实际上已删除了。

如何阻止货件被删除?

4 个答案:

答案 0 :(得分:23)

before_destroy回调需要一个真/假值来确定是否继续进行。

return false添加check_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 

答案 1 :(得分:5)

我的2美分发货.rb

has_one :invoice, dependent: :restrict

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

答案 2 :(得分:3)

来自docs

  

如果before_ *回调返回false,则取消所有后续回调和相关操作。

所以试试这个:

self.errors[:base] << "Cannot delete shipment while its invoice exists." and return false

答案 3 :(得分:1)

对于Rails 4:

class Shipment < ActiveRecord::Base
  has_one :invoice, dependent: :restrict_with_error

会做到这一点。如果您想要异常而不是错误,请使用:restrict_with_exception。请参阅the relevant api docs page

对于Rails 3(可能更早)尝试:

class Shipment < ActiveRecord::Base
  has_one :invoice, dependent: :restrict