除非父母也被删除,否则rails防止删除孩子 [英] rails prevent deletion of child unless parent is being deleted also
问题描述
在Ruby on Rails 4中,假设父母有很多孩子.删除父级后,还必须删除子级.除此之外,除非是孤儿,否则不得删除该孩子.该怎么做?
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?
我尝试了以下方法
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检查,不会删除任何内容.有什么方法可以告诉这个方法,是否被调用的原因是由于父删除?
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.
推荐答案
Working from carp's answer from Rails: how to disable before_destroy callback when it's being destroyed because of the parent is being destroyed (:dependent => :destroy), try this:
孩子:
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
会硬删除而不是软删除它们.我的直觉告诉我,有更好的方法可以做到这一点,但这并不明显,这可以完成工作.
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.
这篇关于除非父母也被删除,否则rails防止删除孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!