首页 > 解决方案 > Rails 有很多关联验证

问题描述

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

在我的 user.rb

accepts_nested_attributes_for :histories
has_many :histories

我需要在用户模型更新时为历史添加验证,我知道accepts_nested_attributes在通过表单添加用户时会处理验证,我需要在每次用户模型更新时检查验证,即使在控制台中,

如果我添加

validates :histories, presence: true

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

标签: ruby-on-railsvalidationactiverecordassociationsmodel-associations

解决方案


根据您的描述,我认为您可能正在寻找的是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

推荐阅读