私は2つのモデルを持っています。
- Parent
has_manyChildren
;
- Parent
accepts_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
#=> []
が、それはバグですか?
質問は何ですか。問題はそれを修復する最良の解決策です。私のアプローチは、Child
にbefore_destroyフィルターを追加して最後のものかどうかを確認することです。しかし、それはシステムを複雑にします。
それでも 'Child'側で妥当性を確認する方が良いです:)感謝 – fl00r
と' marked_for_destruction? 'のおかげで – fl00r
この検証方法はまだRails 3.0.6で必要です – astjohn