I got duplicate validation errors when use accepts_nested_attributes_for in both models. Could I avoid this?

126 Views Asked by At

I have the following models:

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

When I do the following steps:

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

I get duplicate errors:

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

Is there any universal way to avoid such behavior?

(Removing accepts_nested_attributes_for from one of the models is not the solution for me, and I need .user calling too)

0

There are 0 best solutions below