【问题标题】:Rails: _destroy attribute in a nested model skips validates_presence_ofRails:嵌套模型中的 _destroy 属性跳过 validates_presence_of
【发布时间】:2010-12-03 22:59:36
【问题描述】:

我正在关注Nested Model Form Part 1

但我有一个问题。

如果我添加validates_presence_of :answers:

class Question < ActiveRecord::Base
 belongs_to :survey
 validates_presence_of :answers
 has_many :answers, :dependent => :destroy
 accepts_nested_attributes_for :answers, 
        :reject_if => lambda { |a| a[:content].blank? },  
        :allow_destroy => true
end

_destroy 跳过问题模型验证。所以我可以用空答案更新问题模型。

我可能做错了。我该如何解决?

提前致谢。

【问题讨论】:

    标签: ruby-on-rails nested-forms


    【解决方案1】:

    我想你不想:validates_presence_of :answers,我想你想要:validates_associated :answers,它将运行Answer的验证。

    【讨论】:

    • 实际上,我使用了: validates_associated :answers 和 validates_length_of :answers, :minimum => 1. validates_presence_of 我只是为了方便说明而使用的。 validates_associated 只验证关联是否有效,不验证关联是否存在
    【解决方案2】:

    我也问过这个问题并找到了答案。

    此链接更好地描述了问题(来自我的问题)并且也有答案。 http://homeonrails.com/2012/10/validating-nested-associations-in-rails/

    基本上他拒绝了那些被标记为销毁的,并计算了剩下的。

    【讨论】:

      猜你喜欢
      • 2020-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多