Nullify all inheritors of the root class on destroy

249 views Asked by At

Given the following:

class Foo < ActiveRecord::Base; end
class Bar < Foo; end
class Baz < Foo; end

Is there a "Rails'y" way to nullify the foreign keys for all Bars and Bazs when a class with has_many :foos is deleted? This doesn't seem to work:

class Quux < ActiveRecord::Base
  has_many :foos, dependent: :nullify
end

I realize I could do this in a before/after_destroy callback, but I was wondering if there's a more canonical way to do it. Thanks!

UPDATE

My current solutions:

class Quux < ActiveRecord::Base
  after_destroy :nullify_foos

  private

  def nullify_foos
    Foo.where(quux_id: id).update_all(quux_id: nil)
  end
end

or

# (results in two queries?)
class Quux < ActiveRecord::Base
  has_many :bars, dependent: :nullify
  has_many :bazs, dependent: :nullify
end
1

There are 1 answers

3
Donovan On

I believe what you meant was :dependent => :destroy in your has_many association.

has_many :foos, dependent: :destroy

This may end up calling :nullify on the back-end, but it will only do so when actually removing the data row isn't viable.

Referenced here: http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html