设计。根据他的电子邮件自动创建用户名 [英] Devise. Create username automatically based on his email

查看:138
本文介绍了设计。根据他的电子邮件自动创建用户名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以通过使用devise自动创建基于他的电子邮件的用户名吗?

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

在注册页面上,我只有电子邮件和密码字段。

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

例如,当用户通过电子邮件创建一个新帐户 randomname@gmail.com
我希望他的用户名自动成为 randomname 。如何实现?

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?

推荐答案

您可以使用正则表达式获得电子邮件地址的第一部分,如 ^ [^ @] + ,这将从 @ 标志之前的字符串开头返回所有内容。

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

这篇关于设计。根据他的电子邮件自动创建用户名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆