has and belongs to many - rails prevent deletion of child unless parent is being deleted also -
in ruby on rails 4, let's parent has many children. when parent deleted, children must deleted. other that, child shall not deleted unless orphan. how that?
i tried 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 before_destroy check, however, nothing gets deleted. there way of telling method if reason of being called because parent deletion?
is odd thing ask for? mean, preventing deletion of childs.
working carp's answer rails: how disable before_destroy callback when it's being destroyed because of parent being destroyed (:dependent => :destroy), 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 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 because we're using paranoia, , dependent: delete_all
hard-delete rather soft-delete them. gut tells me there's better way this, it's not obvious, , gets job done.
Comments
Post a Comment