简体   繁体   English

Rails 2.3中的自定义唯一性验证

[英]Custom uniqueness validation in Rails 2.3

I'm trying to write a validation in Rails 2.3. 我正在尝试在Rails 2.3中编写验证。

I have two fields, let's call them record_id and user_id. 我有两个字段,我们称它们为record_id和user_id。

The record_id will have both a user_id associated as well as a Name property. record_id将同时具有关联的user_id和Name属性。

The validation should check that when a user creates a new record, that the Name property hasn't already been used. 验证应检查用户创建新记录时是否尚未使用Name属性。 If the user_id is the same BUT the record_id is different, an error should be raised when a user tries to enter a non-unique Name. 如果user_id是相同的,但record_id是不同的,则当用户尝试输入非唯一名称时会引发错误。

If the record_id and user_id is the same and the user tries to create a Name that's already in the database, then the user should be allowed to user a Name that's already in use. 如果record_id和user_id相同,并且用户尝试创建数据库中已经存在的名称,则应允许该用户使用已在使用的名称。

I'm fairly new to Rails 2.3 so ANY guidance at all is most appreciated. 我是Rails 2.3的新手,因此非常感谢任何指导。

那么...您想允许每个用户使用多个名称,检查用户名称是否重复?

validates_uniqueness_of :name, :scope => :user_id

Add unique index on [:user_id, :name] on database side. 在数据库侧的[:user_id,:name]上添加唯一索引。

validate_uniqueness has a heavy performance impact - it adds select on any record create or update, and, in reality, does not guarantee anything for concurrent updated validate_uniqueness对性能产生重大影响-它会在创建或更新的任何记录上添加选择,实际上,对于并发更新,它不做任何保证

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM