Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I prevent deletion of parent if it has child records?

I have looked through the Ruby on Rails guides and I can't seem to figure out how to prevent someone from deleting a Parent record if it has Children. For example. If my database has CUSTOMERS and each customer can have multiple ORDERS, I want to prevent someone from deleting a customer if it has any orders in the database. They should only be able to delete a customer if it has no orders.

Is there a way when defining the association between models to enforce this behavior?

like image 789
Rob Avatar asked Oct 29 '10 16:10

Rob


People also ask

What happens to child record when parent record is deleted?

If we delete record A (First Master detail relationship is always primary) – then child record c will be deleted. If we delete record B then in this case also child record C will be deleted.

What happens when a parent record is deleted in the parent child model having a lookup relationship between parent/child objects?

Parent and child records have their own sharing and security settings in look-up relationships. If the parent record in a lookup relationship is deleted, the field history tracking for the child record does not record the deletion.

What happen if child have two master records and one is deleted?

If child record has two lookup (two parents) then if anyone of them is deleted, child will not be deleted. However, in case of Junction Object where one child has two Master detail relationship (two Parents), even one of them is deleted then Child will be deletd.

When you delete a parent record you will also delete the child record the if the child record has a lookup relationship to the deleted record True or false?

Hi, In a Master-Detail relationship, when a master record is deleted, the detail record is deleted automatically (Cascade delete). In a Lookup relationship, even if the parent record is deleted, the child record will not be deleted.


1 Answers

class Customer < ActiveRecord::Base   has_many :orders, :dependent => :restrict # raises ActiveRecord::DeleteRestrictionError 

Edit: as of Rails 4.1, :restrict is not a valid option, and instead you should use either :restrict_with_error or :restrict_with_exception

Eg.:

class Customer < ActiveRecord::Base   has_many :orders, :dependent => :restrict_with_error 
like image 60
Mauro Avatar answered Sep 21 '22 12:09

Mauro