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


#1

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


#2

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.


#3

Another option is using the before_destroy callback to do the check:
http://apidock.com/rails/ActiveRecord/Callbacks/before_destroy

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