If you want to absolutely ensure uniqueness in Ruby before saving the record, then wrap it in a transaction and lock the tables. 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.