Rails有很多关联验证

时间:2018-11-06 15:52:34

标签: ruby-on-rails validation activerecord associations model-associations

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

在我的user.rb

accepts_nested_attributes_for :histories
has_many :histories

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

如果我添加

validates :histories, presence: true

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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

validates :attribute, presence: true验证程序旨在验证模型上的一流属性,而不是关系。最好在User类validates :email, presence: true上使用。

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

如果您的目标是验证具有很多关系,则可能需要编写自定义验证方法。但是,您能否分享更多有关您要完成的任务的确切信息/您要验证的has_many关系的内容?