Here are two classes, 1:n relation
class Company < AR::Base
has_many :brands
validates_associated :brands
end
class Brand < AR::Base
belongs_to :company
validates_presence_of :name
end
I try to add brands for a company. If the brand name is empty, it gives me duplicated error messages.
c = Company.find(1)
c.valid?
# => true
c.brands.new
# => #<Brand id: nil, name: nil, company_id: 1, created_at: nil, updated_at: nil>
c.valid?
#=> false
c.errors.full_message
#=> ["Brands is invalid", "Brands is invalid"]
c.brands.last.errors.full_message
#=> ["Name required"]
Validates associated can be achieved by two ways
First Option Simple:
has_many :brands, validate: true
Second Option is using validates_associated which will cause duplicate error message and can be avoided by explicitly setting validate to false:
has_many :brands, validate: false
validates_associated :brands
Note:
You can go for second option if you need any additional options like validates_associated :if, :unless etc... otherwise go with first option which will not cause duplicate errors.
A quick workaround to just remove duplicates from the array:
c.errors.full_messages.uniq
#=> ["Brands is invalid"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With