相关疑难解决方法(0)

嵌套模型和父级验证

我有两个型号.
- 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
Run Code Online (Sandbox Code Playgroud)

我使用验证来验证每个父母的孩子的存在,所以我不能保存没有孩子的父母.

parent = Parent.new :name => "Jose"
parent.save
#=> false
parent.children_attributes = [{:name => "Pedro"}, {:name => "Emmy"}]
parent.save
#=> true
Run Code Online (Sandbox Code Playgroud)

验证工作.然后我们将通过_destroy属性摧毁孩子:

parent.children_attributes = {"0" => {:id => 0, :_destroy => true}}
parent.save
#=> true !!!
parent.reload.children
#=> []
Run Code Online (Sandbox Code Playgroud)

所以我可以通过嵌套表单销毁所有孩子,验证将通过. …

ruby ruby-on-rails nested-attributes

40
推荐指数
1
解决办法
2万
查看次数

标签 统计

nested-attributes ×1

ruby ×1

ruby-on-rails ×1