How to Generate a Random 9-digit User ID in Rails4+devise

Asked 2 years ago, Updated 2 years ago, 111 views

I'm a beginner.

In the device, there is a standard "id", which is 1.2.3.4... in the order of registration.

Apart from this, I would like to add the column "userid" and automatically generate it when I register as a member.

The nine-digit random number is

n=9
format("%0#{n}d", SecureRandom.random_number(10**n))

I'm thinking of creating it in

Where and how should I write this to register it as user information?

Thank you.

ruby-on-rails devise

2022-09-30 20:48

1 Answers

It is recommended to use callback in the model class.Callback is described, for example, in the Active Record Callback-Rails Guide.

class User<ActiveRecord::Base
  before_create —generate_userid

  private
  default_userid
    self.userid= (Generate User ID)
  end
end


2022-09-30 20:48

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.