除非父项被删除,否则rails会阻止删除子项

时间:2014-04-14 15:27:46

标签: ruby-on-rails-4 has-and-belongs-to-many dependent-destroy

在Ruby on Rails 4中,假设父母有很多孩子。删除父项后,还必须删除子项。除此之外,除非儿童是孤儿,否则不得删除儿童。怎么做?

我尝试了以下

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

然而,使用before_destroy检查,没有任何内容被删除。如果被调用的原因是因为父删除,有没有办法告诉这个方法?

要求这是一件奇怪的事吗?我的意思是,防止删除孩子。

1 个答案:

答案 0 :(得分:6)

从鲤鱼的Rails: how to disable before_destroy callback when it's being destroyed because of the parent is being destroyed (: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会硬删除而不是软删除它们。我的直觉告诉我,这是一个更好的方法,但这并不明显,这就完成了工作。