2010-09-10 95 views
0

有一个嵌套的形式中,该关系是像这样嵌套窗体 - 如何基于子模型上的输入验证父模型?

class Inspection < ActiveRecord::Base 
    has_many :inspection_components 
    accepts_nested_attributes_for :inspection_components 

class InspectionComponent < ActiveRecord::Base 
    belongs_to :inspection 

我在检查一个自定义的验证方法,其取决于为InspectionComponent输入的属性。我如何验证 - InspectionComponent属性在检验验证中未保存或可用。

谢谢!

编辑:为了让事情更清楚些,下面是我想要做的一个例子。

检查具有属性状态。 InspectionComponent也有一个属性状态。

检查编辑表单嵌套了InspectionComponents,并且可以更新此表单上的每个模型的状态。如果@ inspection_component.status =='complete',@ inspection.status应该只能标记为'complete'。

因此,在验证@inspection时,我必须能够看到用户为@ inspection_component.status输入的内容。

很明显,我可以访问控制器中两个实例的参数,但是在应该进行验证的模型中,我没有看到实现这种情况的方法。

希望这很清楚,谢谢。

+0

我的回答有帮助吗? – DJTripleThreat 2010-09-11 07:54:46

+0

这是的,但它没有解决整个问题,请在下面的帖子下面看到我的评论。谢谢。 – 46and2 2010-09-12 06:41:55

回答

0

您想使用validates_associated

大概是这样的:

validates_associated :inspection_components 

做就可以搜索和查找的API。这种方法也有一些有用的选项。

+0

嗨 - 感谢您的回复。这里的问题是,这仍然是互相独立进行验证。我的意思是,在Inspection验证中,您不知道InspectionComponent子项中发生了什么变化,反之亦然,在InspectionComponent验证中,您不确定已向Inspection父级提交了什么内容。 – 46and2 2010-09-10 00:57:10

+0

嗯...我可能需要看到更多的代码才能更好地理解你想要做什么。你可以编辑你的文章或给我更多关于你想要做的事情的信息吗?通常,我会从'rails my_app'向''这样的文件发布逐步的指令:',这给我一个很好的答案。 – DJTripleThreat 2010-09-10 01:27:24

+0

嗨DJTripleThreat - 我已经更新了OP,希望能够更清楚我想要做什么,感谢您的期待。 – 46and2 2010-09-10 01:44:51

1

好的,一个新的答案,以防我发布的另一个对其他人有用。具体为您的问题,我认为你需要这样的事情:

class Inspection < ActiveRecord::Base 
    has_many :inspection_components 
    accepts_nested_attributes_for :inspection_components 

    # we only care about validating the components being complete 
    # if this inspection is complete. Otherwise we don't care. 
    validate :all_components_complete, :if => :complete 

    def complete 
    self.status == 'complete' 
    end 

    def all_components_complete 
    self.inspection_components.each do |component| 
     # as soon as you find an incomplete component, this inspection 
     # is INVALID! 
     Errors.add("field","msg") if component.status != 'complete' 
    end 
    end 
end 

class InspectionComponent < ActiveRecord::Base 
    belongs_to :inspection 
end 
+0

嗨DJTT,再次,谢谢。有趣的是,这种类型的验证策略确实可以用于创建检查并且它是InspectionComponents,但是一旦情况是更新,我似乎无法访问验证方法中的子项InspectionComponents * updated *属性(all_components_complete )。当我调试并检查每个inspection_component时,它们仍然具有旧的值。 – 46and2 2010-09-12 05:22:09

+0

好吧,让我再想一想,看看我能想出什么。 **编辑:**我得到这个为我工作。如果您发布了您的电子邮件地址,我会通过电子邮件向您发送我建立的项目。我想你可能在你的观点上做错了什么,或者在你尝试更新它们之前用属性做某件事。 – DJTripleThreat 2010-09-13 07:59:20

相关问题