Rails prevent the removal of a child if the parent is not removed as well

in Ruby on Rails 4, let's say a parent has many children. When a parent is removed, children must also be removed. In addition, the child should not be removed unless he is an orphan. How to do it?

I tried 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 

However, before_destroy checks nothing is deleted. Is there a way to report this method if the cause of the call is parental deletion?

Is this a strange thing to ask for? I mean, preventing the removal of child elements.

+6
ruby-on-rails-4 has-and-belongs-to-many
source share
1 answer

Working with carp's answer from Rails: how to disable the before_destroy callback when it is destroyed due to the destruction of the parent (: depend =>: destroy) , try the following:

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 are using Paranoia, and dependent: delete_all will delete hard, not soft-delete. My gut tells me that there is a better way to do this, but it is not obvious, and it does its job.

+5
source share

All Articles