我有兩個模型。
- 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