ruby on rails -密码的活动记录条件验证



我创建了一个项目,允许用户通过添加他们的电子邮件来邀请其他用户。当他们添加他们的电子邮件时,一个用户被创建。但是,我在跳过验证时遇到了一些问题。

在邀请上,我想跳过密码验证。因为只需要邮件。我使用BCrypt和has_secure_password。有人知道怎么跳过这个吗?

我invitations_controller

:

def create
  @user = User.new(invite_params)
  if @user.save
    @user.create_invitation_digest
    @user.send_invitation_email
    flash[:success] = 'User invited'
    redirect_to new_invitation_path
  else
    flash.now[:danger] = 'Unable to invite'
    render 'new'
  end
end

和我的用户模型:

validates :name, presence: true, length: { maximum: 50 }, unless: :invited?
VALID_EMAIL_REGEX = /A[w+-.]+@[a-zd-]+(.[a-zd-]+)*.[a-z]+z/i
validates :email, presence: true, length: { maximum: 255 },
                  format: { with: VALID_EMAIL_REGEX },
                  uniqueness: { case_sensitive: false }
has_secure_password
validates :password, presence: true, length: { minimum: 6 }, allow_nil: true
belongs_to :company
def invited?
 controller_name = 'invitations'
end

一种方法是从模型中删除 has_secure_password并更改密码验证,如下所示。

validates :password, presence: true, length: { minimum: 6 }, allow_nil: true, unless: :invited?

如果需要has_secure_password提供的密码 确认检查,则手动提供密码确认验证,如下所示。

validates_confirmation_of :password

您也可以编写自己的自定义认证如下所示,如果您需要has_secure_password提供的密码认证

def password=(password_str)
  @password = password_str
  self.password_salt   = BCrypt::Engine.generate_salt
  self.password_digest = BCrypt::Engine.hash_secret(password_str, password_salt)
end
def authenticate(password)
  password.present? && password_digest.present? && password_digest == BCrypt::Engine.hash_secret(password, password_salt)
end

你也可以这样做:

在model中声明一个属性,并在controller中设置其值为true。只有在model的值为false时才执行has_secured_password。

user.rb:

attr_accessor: skip_validation // Add this line
has_secured_password, :unless => :skip_validation  // Add IF condition here

user_controller.rb

def create
@user = User.new(invite_params)
@user.skip_validation = true // Add this line
  if @user.save
    @user.create_invitation_digest
    @user.send_invitation_email
    flash[:success] = 'User invited'
    redirect_to new_invitation_path
  else
    flash.now[:danger] = 'Unable to invite'
    render 'new'
  end
end

最新更新