Forum: Ruby on Rails prevent an object from being destroyed if it has related records

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Bbf55d9960b9905e57621d5da6727b2d?d=identicon&s=25 Neal L (Guest)
on 2009-03-29 18:11
(Received via mailing list)
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!
6fabb84e727dee98d1277df56458cbac?d=identicon&s=25 Andrew Bloom (Guest)
on 2009-03-29 18:31
(Received via mailing list)
You could always use inheritance.

class Book < ActiveRecord::Base
  def destroy
    return super if page.empty?
    return false
  end
end
059ed46172a087063ce26250e44c8627?d=identicon&s=25 Fernando Perez (fernando)
on 2009-03-29 19:18
Andrew Bloom 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
059ed46172a087063ce26250e44c8627?d=identicon&s=25 Fernando Perez (fernando)
on 2009-03-29 19:23
> I think you can refactor it to:
>
> def destroy
>   page.empty? || super
> end

My bad:

page.empty? && super

untested though :-)
Dd2d775dea75b381edb1bbf0600a0907?d=identicon&s=25 Marnen Laibow-Koser (marnen)
on 2009-03-30 06:58
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
marnen@marnen.org
http://www.marnen.org
This topic is locked and can not be replied to.