[英]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: 我认为发生了什么事:
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.