开发者

Rails - Saved uuid's length is shorter than 32 characters

I am looking to generate an ID that is not guessable (i.e. long string of random characters).

I am currently using https://github.com/sporkmonger/uuidtools:

app/helpers/uuidhelper.rb

require 'rubygems'
require 'uuidtools'
module UuidHelper
  def before_create()
    self.id = UUIDTools::UUID.random_create().to_s
  end
end

app/models/mymodel.rb

include UuidHelper

However, this is not giving me the desired ef开发者_StackOverflowfect, i.e. length is always too short.

Is there a way to use adapt this to force larger values? Is there another approach that I should be using?

I am currently using SQLite for my development database. Could this have some effect?

I also assume that I should check if the ID exists already before assigning it to a new instance?


You can use:

require 'digest/sha1'
#to check if generated id is unique
self.id = Digest::SHA1.hexdigest(DateTime.now.to_s)[0..length-1] while (ModelName.find(self.id))

where length - desired length of output UUID, also you must check it to be unique( which could be false, if length is too small) and ModelName - name of your model


It was the SQLite database that was causing the issue - moved to MySQL database and it works as expected.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜