Why no :dependent => :delete for has_one?

Is there a reason why the :dependent option for has_one accepts :destroy and :nullify but not :delete?


Jonathan Viney wrote:

Is there a reason why the :dependent option for has_one accepts :destroy and :nullify but not :delete?

The :delete_all option for :has_many sweeps through all the children in one fell SQL swoop, and doesn't call any of the children's 'destroy' callbacks. This is a handy optimisation for when you need to delete a load of records efficiently, and you don't have any callbacks.

But with just one child, calling destroy rather than delete probably doesn't incur much of a extra performance penalty, and it's arguably 'safer' since you're calling all of the callbacks.

I don't think there's any technical reason why you couldn't have a :delete option for has_one, but I guess it just wasn't deemed necessary.


It's also not much code to do effectively the same thing with a callback:

# User    before_destroy { |u| Avatar.delete(u.avatar.id) unless u.avatar.nil? }    has_one :avatar

For consistency, a :delete option on a has_one association seems like a good thing. I took a look at doing a patch to add that to AR and it was pretty simple, but I gave up when I had to deal with the brittle fixtures used for AR test cases. Sigh.

I brought this up in the comments to:

<Peak Obsession;

But I agree, it would be nice to have for consistency but isn't really necessary for deleting just one child.

Shane Vitarana shanesbrain.net

Josh Susser wrote:

Fantastic! I had the same experience as you guys. The patch took about a minute… then I saw how badly all the test cases broke and decided to come back to it later!