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..
Asked
Active
Viewed 3,351 times
2
-
1You 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 Answers
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
-
-
-
yep, before_destroy maybe more appropriate here. updated answer accordingly. – aguynamedloren Mar 27 '13 at 09:24
-
-
`self` is unnecessary here, it is implied. the reason it works is because ruby tries to find a local variable (ie `dog`) and if it doesn't find it, it sends it to `self`. try it and see :) – aguynamedloren Mar 27 '13 at 09:50
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

Rodrigo de Sá
- 1
- 1