【发布时间】:2011-07-05 21:31:36
【问题描述】:
我有两个模型。
- 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属性销毁孩子:
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
#=> []
是bug吗?
这是什么问题。问题是修复它的最佳解决方案。我的方法是将 before_destroy 过滤器添加到Child 以检查它是否是最后一个。但它使系统变得复杂。
【问题讨论】:
标签: ruby-on-rails ruby nested-attributes