我正在尝试在模型上实现 before_destroy。当我关注这个 before_destroy example 时,我要么收到一个 NameError 要么最终得到一些不做 before_destroy 的东西。我的语法有什么问题?

class Person < ActiveRecord::Base

  has_many :book_loans, :order => 'return_date desc'
  has_many :books, :through => :book_loans

  before_destroy
    errors.add_to_base "Cannot delete borrower with loans" unless
                                                           book_loans.count == 0
end

不编译
  before_destroy
    errors.add_to_base "Cannot delete borrower with loans" unless
                                                           book_loans.count == 0

不起作用
def before_destroy
  errors.add_to_base "Cannot delete borrower with loans" unless
                                                         book_loans.count == 0
end

最佳答案

您不能添加错误 before_destroy ,因为它们不会影响验证。您必须在验证发生之前添加错误,例如before_validation

还有一些额外的回调, before_validation_on_createbefore_validation_on_update 。但是,没有 on_destroy 版本,因为 savevalid? 从未被调用,因此在您尝试销毁某些内容时添加验证错误将毫无意义。

换句话说:您的 before_destroy 运行,但它不会影响任何事情,因为在您销毁记录时没有检查验证错误。

下面是一种基于某些条件实现防止记录保存的方法。

before_destroy :require_no_book_loans

private

def require_no_book_loans
  raise ActiveRecord::RecordInvalid unless book_loans.count == 0
end

您还可以创建自己的错误类并提出该错误。

仅供引用:您应该在语法错误示例中将一个块传递给 before_destroy
before_destroy {|r|
  r.errors.add_to_base "Foo" # ...
}

关于ruby-on-rails - Ruby on Rails before_destroy 导致 NameError,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1479068/

10-13 09:14