Prevent an object from being destroyed if it has related records


#1

This is a total noob question, but how do you prevent a record from
being destroyed if it has any related records. In my case, I have a
book model and a page model. A book has_many pages.

How do I prevent book.destroy from destroying a book if it has
associated page records? Is there a :dependent option that would do
this? Do I need to do some sort of before destroy callback?

Thanks!


#2

You could always use inheritance.

class Book < ActiveRecord::Base
def destroy
return super if page.empty?
return false
end
end


#3

Andrew B. wrote:

You could always use inheritance.

class Book < ActiveRecord::Base
def destroy
return super if page.empty?
return false
end
end
I think you can refactor it to:

def destroy
page.empty? || super
end


#4

I think you can refactor it to:

def destroy
page.empty? || super
end

My bad:

page.empty? && super

untested though :slight_smile:


#5

Neal L wrote:

This is a total noob question, but how do you prevent a record from
being destroyed if it has any related records.

The database layer can do this easily, so harness its power! Put a
foreign key constraint in your DB with ON DELETE RESTRICT. The Railsy
way to do this is with the excellent foreign_key_migrations plugin (see
http://github.com/harukizaemon ) – which you should probably be using
in any case. It works with mySQL and PostgreSQL; I’m not sure about
other database systems.

Best,

Marnen Laibow-Koser
removed_email_address@domain.invalid
http://www.marnen.org