Rails 3. checking before_destroy to prevent parent records from being deleted

I have shipment and invoice.

the invoice belongs to the shipment
Shipment has one invoice

If the shipment has an invoice, the shipment of the goods cannot be deleted. I need to install this in models because I use ActiveAdmin.

So, I did it in the shipment.rb file

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 

But I just get a yellow message saying "Sending cannot be deleted", but it was actually deleted.

How can I prevent sending from being deleted?

+8
ruby ruby-on-rails ruby-on-rails-3
source share
4 answers

The before_destroy requires true / false to determine if the proxy should be executed.

Add return false to your check_for_invoice like this:

 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 
+23
source share

My 2 cents at shipment.rb

 has_one :invoice, dependent: :restrict 

I think this will work, I saw this solution in a different thread. Now I am trying in my models.

+4
source share

From docs :

If the before_ * callback returns false, all subsequent callbacks and the associated action are canceled.

So try the following:

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

For Rails 4:

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

will do the trick. If you want an exception instead of an error, use :restrict_with_exception . See the corresponding api docs page for more details.

For Rails 3 (maybe earlier) try:

 class Shipment < ActiveRecord::Base has_one :invoice, dependent: :restrict 
+1
source share

All Articles