问题描述
我有一个具有相同表结构的Company
和Archive
模型.两种模型均具有validates :name, :uniqueness => true
验证.
I have a Company
and Archive
model that have the same table structure. Both models have a validates :name, :uniqueness => true
validation.
在company.rb文件中,我无法设置自定义验证,在该记录中,当我将记录添加到Company
数据库时,它还会检查Archive
模型(因此,如果Archive模型中的记录包含该名称已经存在,则不会添加到Company
表中.)
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?
推荐答案
company.rb
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.
这篇关于验证两个表之间的唯一性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!