Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating Uniqueness Across Two Tables

I have a Company and Archive model that have the same table structure. Both models have a validates :name, :uniqueness => true validation.

In the company.rb file I'm having trouble setting up a custom validation where when I add a record to the Company database it also checks the Archive model (so that if a record in the Archive model with that name already exists then it won't be added to the Company table).

I'm assuming this is possible to do, but I'm having trouble implementing, can anyone help?

like image 911
Reuben Avatar asked Jul 31 '26 11:07

Reuben


1 Answers

company.rb

validates :name, uniqueness: true

validate :unique_name

def unique_name
  self.errors.add(:name, 'is already taken') if Archive.where(name: self.name).exists?
end

It is important to remember though that such code level Unique constraints may not work in a race condition among parallel requests unless somehow this can be done at database level.

like image 168
Santhosh Avatar answered Aug 02 '26 06:08

Santhosh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!