2011-04-12 80 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