0

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
Kaleidoscope
  • 3,609
  • 1
  • 26
  • 21

1 Answers1

0

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

Donovan
  • 15,917
  • 4
  • 22
  • 34
  • I want a guarantee from Rails that all `Foo`s will only be nullified though. – Kaleidoscope Dec 12 '13 at 20:22
  • Actually, I think you're right, I'm not sure rails will follow the up the hierarchy tree the way you want it to. You'll probably need to use a callback method to guarantee your results. Test it out? Now, I'm curious. – Donovan Dec 12 '13 at 20:25
  • The way I'm imagining it, it wouldn't be going up the hierarchy, but rather going down to anything that inherits from it. Seems plausible given that Rails is already smart enough to implement STI. – Kaleidoscope Dec 12 '13 at 20:35