1

我在注册过程中使用了 Devise gem - 我只希望电子邮件是必需的,所以我会为每个用户自动生成密码。

出于某种原因,我的代码正在为单个用户创建 2 个数据库条目。一 - 使用电子邮件地址。一——只有加密的密码。

用户.rb

password = Devise.friendly_token
  User.create!(:email => @current_user_email, :id => @current_user_id, :password => password, :password_confirmation => password)


  before_save { |user| user.email = email.downcase }

  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false }
4

1 回答 1

2

在我的一个项目中,我采取了类似的方法,不要求用户使用密码进行注册。它导致了一些主要的头痛和 UX 恶作剧 FWIW。

无论您使用什么来进行持久化,请确保在电子邮件列上设置唯一索引。这将导致异常,但它们很容易处理。

我建议在您的用户模型中使用一个类方法,例如:

class User
  def self.create_without_password!(email)
    password = Devise.friendly_token
    User.create!(:email => email.downcase, :password => password, :password_confirmation => password)
  end
end

这应该在不使用 before_save 回调的情况下验证模型并引发非唯一性异常

于 2012-09-11T19:45:23.920 回答