Ruby on Rails before_destroy raises a NameError

I am trying to implement before_destroy on a model. As long as I follow the before_destroy example, I either get a NameError or get what before_destroy does not. What is wrong with my syntax?

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 

Not compiled

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

Does not work

 def before_destroy errors.add_to_base "Cannot delete borrower with loans" unless book_loans.count == 0 end 
+4
source share
1 answer

You cannot add before_destroy errors because they will not affect the validation. You must add errors before validation occurs. before_validation .

There are several additional callbacks before_validation_on_create and before_validation_on_update . However, there is no version of on_destroy , because save and valid? never called, so adding validation errors when trying to destroy something would be pointless.

In other words: your before_destroy , but it has no effect, because nothing checks for validation errors when deleting records.

Here you take on the implementation of something that prevents the recording from being saved under certain conditions.

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

You can also create your own error class and raise it.

FYI: you must pass the before_destroy block to your syntax error example.

 before_destroy {|r| r.errors.add_to_base "Foo" # ... } 
+6
source

All Articles