Ruby on rails 轨道3。在销毁验证以防止删除父记录之前

Ruby on rails 轨道3。在销毁验证以防止删除父记录之前,ruby-on-rails,ruby,ruby-on-rails-3,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 shipm

我有货物和发票

发票属于发货
这批货有一张发票

如果装运具有发票,则装运不应被删除。我需要在模型中设置它,因为我使用的是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
has_one :invoice, dependent: :restrict
有一个:发票
销毁前:检查发票
私有的
def检查发票
除非发票。零?
来自以下位置的self.errors[:base]:

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

所以试试这个:

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

self.errors[:base]销毁前的
回调需要一个真/假值来确定是否继续

在您的
检查发票
中添加
return false
,如下所示:

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 
有一个:发票
销毁前:检查发票
私有的
def检查发票
除非发票。零?

self.errors[:base]我的发货中的2美分.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
has_one :invoice, dependent: :restrict
我认为它会起作用,我在另一个线程中看到了这个解决方案。我现在正在尝试我的模型。

对于Rails 4:

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

啊,没错!我忘了返回false。我还错误地发布了这部分代码
if invoice.nil?
,应该是
,除非invoice.nil?
。我对逻辑很好奇,但我认为这可能是你在做的奇怪的事情。我会更新我的答案,使之与后人相匹配。检查一个更好的方法来做这件事。@约旦,你是正确的,<代码>返回<代码>在Ruby中大多不是习惯用法,但是如果该行不是方法中的最后一行(加上考虑重构),该怎么办?或者,如果您后来在方法中添加了其他语句,而忘记了添加返回,该怎么办?我认为这就是为什么您会在rails项目中看到
并返回false的原因……好吧,这是一个足够有说服力的论点。我已经把复习卷退回了。