2011-04-12 117 views
4

我有两个模型,一个是另一个的父级,父代accept_nested_attributes_for和validates_associated子级。针对父级模型验证模型

但是,我的一些验证中有一个:如果需要检查父项的某个属性。

我在想,我可以做这样的事情:

validates_presence_of :blah, :if => Proc.new{|thing| thing.parent.some_value.present?} 

不过,“父”的关系似乎并没有被设置在验证的时候(我将承担孩子实例化和首先验证。

因此有做什么,我在想什么办法?这可能吗?

回答

1

您可以使用before_update或before_create回调根据自己的需要这样的..

def before_update 
    self.errors.add("Error Message") if self.parent.some_value.present? 
    return false if self.errors.count > 0 
end 

def before_create 
    self.errors.add("Error Message") if self.parent.some_value.present? 
    return false if self.errors.count > 0 
end 
+0

这有效,但缺点是,当被问及是否有效时,即使父母上的值不存在,模型也会回答“真”。 – Matt 2016-10-27 10:24:00

0

这种验证应该工作:

validates_associated:儿童

,但它不会

的原因是,据我了解,beause使用acceptes_nested_attributes_for通过一个事务直接创建嵌套对象到数据库,而不通过任何儿童验证。

你可以在这里做什么:在父模型中编写自己的验证并验证创建子对象。

+0

我认为这是ActiveRecord/Rails 2.3的情况,但不是3.1或3.2。由嵌套属性创建的子对象也被验证。 – graywh 2013-03-30 03:52:06

0

使用:inverse_of选项作为父项的关联,因此子项在构建时会引用父项。

class Parent < ActiveRecord::Base 
    has_many :children, :inverse_of => :parent 
    accepts_nested_attributes_for :children 
end 

class Child < ActiveRecord::Base 
    belongs_to :parent 
end 

p = Parent.new :children_attributes => { 0 => { :child_attribute => 'value' } } 
p.children.first.parent #=> shouldn't be nil anymore