# Protecting an associated record from destroying -- How To and explanation?

**URL:** <https://www.ruby-forum.com/t/protecting-an-associated-record-from-destroying-how-to-and-explanation/162380>\
**Category:** Rails\
**Created:** [March 9, 2009, 1:34pm UTC](https://www.ruby-forum.com/t/protecting-an-associated-record-from-destroying-how-to-and-explanation/162380 "2009-03-09T13:34:16Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [March 9, 2009, 1:34pm UTC](https://www.ruby-forum.com/t/protecting-an-associated-record-from-destroying-how-to-and-explanation/162380/1 "2009-03-09T13:34:16Z")

</div>

Hi,

I have a model “Pattern” with subject and body as columns  
and another “Schedule” with date, time and pattern\_id(for inserting an  
association to Pattern table)

## I had defined it as

## class Schedule \< ActiveRecord::Base has\_one :pattern end

## class Pattern \< ActiveRecord::Base belongs\_to :schedule end

So whenever you need to create a schedule u need to a pattern also.  
Then i removed the pattern which was used by a schedule.  
How can i avoid this action.

I wonder then whats the reason of having these relationships  
Is there any additional things reqd. for me to do

Regards,  
Vimal Das

---

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [March 9, 2009, 2:27pm UTC](https://www.ruby-forum.com/t/protecting-an-associated-record-from-destroying-how-to-and-explanation/162380/2 "2009-03-09T14:27:11Z")

</div>

vimal wrote:

> Then i removed the pattern which was used by a schedule.  
> How can i avoid this action.

As the old family physician used to say, “If it hurts, don’t do it.”

If you want to protect against pattern deletion, you could just  
eliminate the destroy method from the Pattern controller, and make the  
Pattern destroy happen only through the “parent” Schedule destroy.

---

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [March 9, 2009, 2:36pm UTC](https://www.ruby-forum.com/t/protecting-an-associated-record-from-destroying-how-to-and-explanation/162380/3 "2009-03-09T14:36:07Z")

</div>

Another option is using the before\_destroy callback to do the check:  
[http://apidock.com/rails/ActiveRecord/Callbacks/before\_destroy](http://apidock.com/rails/ActiveRecord/Callbacks/before_destroy)

On Mon, Mar 9, 2009 at 9:27 AM, Ar Chron
