2

Say I have dogs, leashes, and owners... If I destroy a leash I want to destroy the dog too.. but not if the dog has an owner..

Abram
  • 39,950
  • 26
  • 134
  • 184
  • 1
    You can use a callback after_destroy for that. See [this answer][1] for details. [1]: http://stackoverflow.com/questions/6049806/rails-aciverecord-use-dependent-destroy-on-condition – davidrac Mar 27 '13 at 09:09
  • Can you call 'self' after_destroy? – Abram Mar 27 '13 at 09:16
  • I didn't try it myself, but I think you can. The model object should still exist even after destroy. – davidrac Mar 27 '13 at 09:23

2 Answers2

4

You don't want to use :dependent => :destroy here, but rather the before_destroy callback like so:

#leash.rb

before_destroy :destroy_dog

def destroy_dog
  dog.destroy unless dog.owner
end
aguynamedloren
  • 2,273
  • 18
  • 23
0
class Book < ApplicationRecord
  belongs_to :author, -> { where active: true },
                        dependent: :destroy
end

works for has_many too, in which it destroys the objects according to the where condition