我有两个模型。
- Parent
has_manyChildren
;
- Parent
accepted_nested_attributes_forChildren
;嵌套模型和父验证
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
以检查它是否是最后一个。但它使系统变得复杂。
但它的更好,然后验证在'Child'侧:)谢谢 – fl00r 2011-02-28 16:45:46
和感谢'marked_for_destruction?' – fl00r 2011-02-28 16:51:06
这种验证方法仍然需要像Rails 3.0.6的 – astjohn 2011-04-21 13:35:42