微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在两个模型中使用 accepts_nested_attributes_for 时出现重复的验证错误我可以避免这种情况吗?

如何解决在两个模型中使用 accepts_nested_attributes_for 时出现重复的验证错误我可以避免这种情况吗?

我有以下型号:

class User < ApplicationRecord
  belongs_to :company

  accepts_nested_attributes_for :company
end
class Company < ApplicationRecord
  has_one :user

  accepts_nested_attributes_for :user,update_only: true

  validates :name,presence: true
end

当我执行以下步骤时:

company.name = nil
company.user
company.valid?
company.errors.full_messages

我收到重复的错误

["Name can't be blank","User company name can't be blank"]

有什么通用的方法可以避免这种行为吗?

(从其中一个模型中删除 accepts_nested_attributes_for 不是我的解决方案,我也需要 .user 调用

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。