8

in Ruby on Rails 4, let's say a parent has many children. When the parent is deleted, the children must also be deleted. Other than that, the child shall not be deleted unless it is an orphan. How to do that?

I tried with the following

class Parent < ActiveRecord::Base
  has_many :children, inverse_of: :parent, dependent: :destroy
end

class Child < ActiveRecord::Base
  belongs_to :parent, inverse_of: :children
  before_destroy :checks
private
  def checks
    not parent # true if orphan
  end
end

With the before_destroy check, however, nothing gets deleted. Is there any way of telling this method if the reason of being called is because parent deletion?

Is this an odd thing to ask for? I mean, preventing deletion of childs.

4

1 回答 1

8

Rails 的 carp 的回答中工作:how to disable before_destroy callback when it's being destroy because the parent is being destroy (:dependent => :destroy),试试这个:

孩子:

belongs_to :parent
before_destroy :prevent_destroy
attr_accessor :destroyed_by_parent

...

private

def prevent_destroy
  if !destroyed_by_parent
    self.errors[:base] << "You may not delete this child."
    return false
  end
end

家长:

has_many :children, :dependent => :destroy
before_destroy :set_destroyed_by_parent, prepend: true

...

private

def set_destroyed_by_parent
  children.each{ |child| child.destroyed_by_parent = true }
end

我们必须这样做,因为我们使用的是偏执狂,并且dependent: delete_all会硬删除而不是软删除它们。我的直觉告诉我有更好的方法可以做到这一点,但这并不明显,这可以完成工作。

于 2014-04-16T15:00:25.940 回答