本文介绍了导轨 - 验证presence协会?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有,有一个的has_many的关联关系模型B.我有一个插入到至少需要1相关的记录B.业务需求模型中的是否有一种方法,我可以打电话,以确保这是真实的,或者我需要编写一个自定义的验证?

I have a model A that has a "has_many" association to another model B. I have a business requirement that an insert into A requires at least 1 associated record to B. Is there a method I can call to make sure this is true, or do I need to write a custom validation?

推荐答案

您可以使用 validates_ presence_of <一个href="http://apidock.com/rails/ActiveModel/Validations/ClassMethods/validates_$p$psence_of">http://apidock.com/rails/ActiveModel/Validations/ClassMethods/validates_$p$psence_of

class A < AR::Base
  has_many :bs
  validates_presence_of :bs
end

或只是只会验证http://apidock.com/rails/ActiveModel/Validations/ClassMethods/validates

class A < AR::Base
  has_many :bs
  validates :bs, :presence => true
end

但有与它的错误,如果你会使用 accepts_nested_attributes_for :allow_destroy =&GT;真正的嵌套模型和家长的验证。在这个主题中,您可以找到解决方案。

But there is a bug with it if you will use accepts_nested_attributes_for with :allow_destroy => true: Nested models and parent validation. In this topic you can find solution.

这篇关于导轨 - 验证presence协会?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 06:40