I have two classes: Parent and Child with
Child:
belongs_to :parent
and
Parent
has_many :children, :dependent
carp's answer above will work if you set prepend to true on the before_destroy method. Try this:
Child:
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
Parent:
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
We had to do this because we're using Paranoia, and dependent: delete_all
would hard-delete rather than soft-delete them. My gut tells me there's a better way to do this, but it's not obvious, and this gets the job done.