我有一个通常的嵌套模型
class Parent
has_one :child
accepts_nested_attributes_for :child
end
class Child
belongs_to :parent
validate :name, :presence => true
end
如果我试图保存一个没有名字的孩子,那么这是禁止的,但是如果我保存了嵌套孩子的父母,如果忽略了验证。
我不想用:reject_if
重复我的孩子验证。
如何验证孩子,并且只有孩子有效时,将父母与孩子一起保存?
答案 0 :(得分:12)
您应该使用validates_associated
:
class Parent
has_one :child
accepts_nested_attributes_for :child
validates_associated :child
end