简体   繁体   English

保存记录前检查唯一值

[英]Check for unique value before saving record

My setup: Rails 3.0.9, Ruby 1.9.2我的设置:Rails 3.0.9、Ruby 1.9.2

I want to generate a unique random number for a column right before creating a new record.我想在创建新记录之前为一列生成一个唯一的随机数。 What is the most efficient way to do this in Ruby?在 Ruby 中执行此操作的最有效方法是什么? I understand that I can use validates_uniqueness_of but I want to ensure uniqueness beforehand.我知道我可以使用 validates_uniqueness_of 但我想事先确保唯一性。

How about a before_create or before_save AR callback? before_create 或 before_save AR 回调怎么样?

Something like:就像是:

class ModelNameHere < ActiveRecord::Base
  before_create :generate_unique_number

  private
    def generate_unique_number
      begin
        self.number = unique_number_generator()
      end while (not ModelNameHere.find_by_number(self.number).blank?)
    end

The begin..end while is basically a do-while loop taken from this answer . begin..end while 基本上是取自这个 answer的一个 do-while 循环。 Haven't tested though but I think it should work.虽然没有测试,但我认为它应该工作。

If you want to absolutely ensure uniqueness in Ruby before saving the record, then wrap it in a transaction and lock the tables.如果您想在保存记录之前绝对确保 Ruby 中的唯一性,则将其包装在事务中并锁定表。 Be aware that this can cause a significant impact on your performance.请注意,这可能会对您的性能产生重大影响。

self.class.transaction do
  connection.execute('LOCK TABLES table_name WRITE')

  # do your random generation until uniqueness validation passes here

  connection.execute('UNLOCK TABLES')
end

Personally, I think I'd rather place a unique constraint on the column in the database and catch the resulting exception in case you encounter a real race condition.就个人而言,我认为我宁愿在数据库中的列上放置一个唯一约束,并在遇到真正的竞争条件时捕获产生的异常。

maybe something like... self is new object也许像......自我是新的 object

Object.currentkeys.each do currentkey 
    if self.key == current.key
   #The key is allready in use

    else
     #You have unique key
    end
end

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

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