Rails有许多关联验证



每次更新父模型时,我都需要检查相关属性的存在性验证。

在我的user.rb 中

accepts_nested_attributes_for :histories
has_many :histories

当用户模型更新时,我需要为历史添加验证,我知道accepts_nested_attributes会在通过表单添加用户时负责验证,我需要在每次用户模型更新(甚至在控制台中(时检查验证

如果我添加

validates :histories, presence: true

它将检查历史记录表中的记录,如果有任何记录可供用户使用它将跳过历史记录的验证,我需要在每次更新对象时进行验证。在更新父模型时,是否有任何方法可以验证是否正在创建新记录?

根据您的描述,我认为您可能正在寻找validates_associated:

class User < ApplicationRecord
has_many :histories
# validates that the association exists
validates :histories, presence: true
# validates that the objects in the associated collection are themselves valid
validates_associated :histories
end

validates :attribute, presence: true验证器用于验证模型上的一流属性,而不是关系。像在用户类validates :email, presence: true上这样的东西,是它最有效的地方。

您的目标是验证has_many关系还是测试关系?如果这是一个测试,您应该制定一个规范,按照it { should have_many(:histories) }…的行运行测试。。。。这显然取决于您的测试框架。

如果您的目标是验证具有多个关系,那么您可能需要编写一个自定义的验证方法。然而,你能分享更多关于你到底想实现什么/你试图验证的has_many关系是什么吗?

最新更新