ruby-on-rails - 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
推荐阅读
- php - CodeIgniter - 在 CBC 模式下使用 AES 时使用静态 IV
- c++ - C++ SFML:如何成功地迭代渲染形状?
- automated-tests - Appium 或 Xamarin UI 测试 - 经验和缺点
- c# - 重定向 302 循环大概是因为负载平衡和 .NET Core 身份验证
- javascript - 如何向文本框添加动态 ID?
- c# - 如何在 Xamarin.Android 中从 EventHandler 获取值到后台服务
- regex - Why isn't this sed command working for the regex?
- python - 如何将 dat 文件格式化为干净的 csv
- jquery - 克隆后如何启用下拉项
- c# - C# - new Shell32() 抛出异常?