I have shipments and invoices.
invoice belongs to shipment
shipment has one invoice
If the shipment does have an invoice, then the shipment shouldn't be able to be deleted. I need to set this up in the models because I'm using ActiveAdmin.
So I did this in shipment.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
But I just get a yellow message saying "Shipment cannot be deleted" but it was in fact deleted.
How can I prevent the shipment from being deleted?
The before_destroy
callback needs a true/false value to determine whether or not to proceeed.
Add a return false
to your check_for_invoice
like so:
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
My 2 cents in shipment.rb
has_one :invoice, dependent: :restrict
I think that it'll work, I saw this solution in another thread. I'm tryng right now in my models.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With