简体   繁体   English

Rails具有_destroy的accepts_nested_attributes_for可以跳过状态验证

[英]Rails accepts_nested_attributes_for with _destroy can skip presence validation

So I have a typical Rails model with accepts_nested_attributes_for with presence validation 所以我有一个带有accepts_nested_attributes_for的典型Rails模型,并且具有在线状态验证功能

(snippets) (片段)

class Book < ActiveRecord::Base
  ...

  has_one :cover
  accepts_nested_attributes_for :cover, allow_destroy: true

  validate :require_cover

  def require_cover
    errors.add('', 'You must have a cover for the book.') if self.cover.blank?
  end

  ...
end

This works and validates okay on the first step when I'm creating. 当我创建时,这可以正常工作并验证第一步。 But when I try to edit it and click delete on the cover (clicking delete adds _destroy true) and save it, it deleted the cover but the validation regarding presence has passed already. 但是,当我尝试对其进行编辑并单击封面上的“删除”(单击“删除”添加_destroy true)并保存时,它删除了封面,但是有关状态的验证已经通过。

I think what happened was: 我认为发生了什么事:

  1. tagged destroy cover 标记的破坏盖
  2. validation process happens (thinks there is still cover (but maybe doesn't recognize destroy)) 验证过程发生(认为仍然存在掩盖(但可能无法识别破坏))
  3. valid and goes to saving 有效并保存
  4. saves book and 保存书和
  5. passes 通行证

No validation again regarding the no cover 再次确认无封面

Have I done this incorrectly? 我做错了吗? Is there another way to implement this? 还有另一种方法可以实现吗? Or how do I revalidate this scenario (like, after the save and destroy that has happened, there would be another validation to say that the resulting object is now invalid)? 还是我如何重新验证这种情况(例如,在发生保存和销毁之后,将再次进行验证以表明结果对象现在无效)?

I found the fix to my question, I was right that the save doesn't take into account those that are tagged as _destroy. 我找到了解决问题的方法,很正确,保存没有考虑那些标记为_destroy的对象。

This link describes the problem better and has the answer to it too. 此链接可以更好地描述问题,并且也可以找到答案。 http://homeonrails.com/2012/10/validating-nested-associations-in-rails/ http://homeonrails.com/2012/10/validating-nested-associations-in-rails/

Basically he rejected those that are marked for destruction and counted the remaining ones. 基本上,他拒绝了那些标有要销毁的物品,并计算了剩余的物品。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM