Implementation of making models have uuid in rails

Asked 2 months ago, Updated 2 months ago, 5 views

Currently, uuid is achieved by adding the following actions to the User model:

def before_save_action_name
    uuid=SecureRandom.uuid while User.exists?(:uuid=>uuuid)

With Ruby's expressive power, I think I can make it in one line (especially where there are two lines that are substituted for uuid),
How would you like it implemented?

ruby-on-rails ruby rails-activerecord

2022-09-30 11:27

3 Answers

The UUID is 128 bits, and for v4 (random), the probability of collision is 0.000001% only after 8.2 x 10^14 units are generated.(Reference table) I think it's expensive to check with exists? every time for such a rare case (of course it should be measured).but)

Wouldn't it be better to put unique restrictions on the DB side and retry in case of save exception?

2022-09-30 11:27

As you can see in this answer, there is very little chance of duplicate UUIDs.So you don't have to consider duplication.

DB has a unique constraint on it, and it's better to try it in case of a save exception

I agree with the first half because there is a possibility that the data may be registered incorrectly for some reason, but I disagree with the second half.You can leave the exception out and let it die.

(However, if there is a request as a general response in the event of a constraint violation, it is not necessary to do so.)

It would be much better to duplicate check the model than to write retry code on the controller for duplicate UUIDs.

2022-09-30 11:27

I also borrowed it from somewhere, but I have implemented it as follows:
To user.rb

before_create: generate_token


  self.uuid=loop do
    random_token = SecureRandom.urlsafe_base64(nil, false)
    break random_token unless self.class.exists?(uuid:random_token)

SecureRandom.urlsafe_base64(nil, false) is a string similar to the following:

SecureRandom.uuid generates a string similar to the following:

I'm concerned that if uuid is generated only once, before_create is better than before_save.
If before_save, it will also be executed by saving create and update.

Is called before (regardless of which it's a create or update save).

2022-09-30 11:27

If you have any answers or tips

© 2022 OneMinuteCode. All rights reserved.