Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicate error messages with validates_associated

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"]
like image 878
Hegwin Avatar asked Dec 20 '22 02:12

Hegwin


2 Answers

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.

like image 160
user2801 Avatar answered Jan 07 '23 10:01

user2801


A quick workaround to just remove duplicates from the array:

c.errors.full_messages.uniq
#=> ["Brands is invalid"]
like image 38
Aaron Tribou Avatar answered Jan 07 '23 10:01

Aaron Tribou