Validating Uniqueness Across Two Tables

2019-08-14 01:51发布

问题:

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?

回答1:

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.