我有两个模型。
- Parent
has_many Children
;
-Parent
接受_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
属性销毁孩子:
parent.children_attributes = {"0" => {:id => 0, :_destroy => true}}
parent.save
#=> true !!!
parent.reload.children
#=> []
所以我可以通过嵌套表单销毁所有孩子并且验证将通过。
实际上发生这种情况是因为在我通过删除父级的子级之后_delete
,子级方法在我重新加载它之前仍然返回销毁的对象,因此验证通过:
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 过滤器Child
来检查它是否是最后一个。但它使系统变得复杂。