I've got two models.
- Parent
has_many Children
;
- Parent
accepts_nested_attributes_for Children
;
class Parent < ActiveRecord::Base
has_many :children, :dependent => :destroy
accepts_nested_attributes_for :children, :allow_destroy => true
validates :children, :presence => true
end
class Child < ActiveRecord::Base
belongs_to :parent
end
我使用验证来验证每个家长是否有子元素,因此我无法保存没有子元素的家长.
parent = Parent.new :name => "Jose"
parent.save
#=> false
parent.children_attributes = [{:name => "Pedro"}, {:name => "Emmy"}]
parent.save
#=> true
验证工作.然后我们将通过_destroy
属性摧毁 children :
parent.children_attributes = {"0" => {:id => 0, :_destroy => true}}
parent.save
#=> true !!!
parent.reload.children
#=> []
所以我可以通过嵌套表单销毁所有子项,验证将通过.
实际上,这是因为在我通过_delete
从父对象中删除子对象之后,children方法仍然会在我重新加载之前返回已销毁的对象,所以验证通过了:
parent.children_attributes = {"0" => {:id => 0, :_destroy => true}}
parent.save
#=> true !!!
parent.children
#=> #<Child id:1 ...> # It's actually deleted
parent.reload.children
#=> []
是虫子吗?
问题是什么.这个问题是修复它的最佳解决方案.我的方法是将before_destroy filter添加到Child
,以判断它是否是最后一个.但这让系统变得复杂.