Devise. Create username automatically based on his

2019-06-05 23:10发布

问题:

Is it possible to created username based on his email automatically by using devise?

On register page, I have only email and password fields.

For example, when user create a new account with email randomname@gmail.com, I'd like that his username automatically become a randomname. How can I accomplish it?

回答1:

You can get the firstpart of the email adress with a regex like ^[^@]+, this will return everything from the start of the string before the @ sign.

^ /* start of string or line */
[^@] /* character class capturing everything except @ */
+ /* match must happen atleast one time */

To add the username to your database, you can use a callback.

class User < ActiveRecord::Base
  before_create :set_username

  private
    def set_username
      self.username = self.email[/^[^@]+/]
    end
end


回答2:

To account for emails that have the same name but different urls you can add a random number at the end.

self.username = "#{self.email[/^[^@]+/]}-#{SecureRandom.hex(1)}"

This will return hoobas-1f an hoobas-3c to the two emails in the comment above.