Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3. before_destroy validation to prevent deleting parent records

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?

like image 648
leonel Avatar asked Jan 11 '12 19:01

leonel


2 Answers

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 
like image 119
Paul Simpson Avatar answered Nov 04 '22 03:11

Paul Simpson


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.

like image 5
josias Avatar answered Nov 04 '22 01:11

josias