代码之家  ›  专栏  ›  技术社区  ›  Madhusudhan

创建时没有密码确认,但更新时需要密码(AuthLogic)

  •  0
  • Madhusudhan  · 技术社区  · 16 年前

    我对Rails比较陌生,并且我正在使用AuthLogic作为我的身份验证系统。我希望在用户更新其配置文件时获得密码确认,但在他注册时没有。

    我找到了这个配置选项

    acts_as_authentic do |c|
      c.require_password_confirmation=false
    end
    

    当我这样做时,它会在注册时忽略密码确认(这很好),但在编辑用户配置文件时,我希望它考虑密码确认字段。有什么方法可以配置这个吗?

    1 回复  |  直到 16 年前
        1
  •  1
  •   bjg    16 年前

    由于暂停了基于AuthLogic的验证,您可以使用标准Rails模型验证来实现这一点,例如:

    validates_presence_of :password_confirmation, :if => :password_required?
    

    何处 password_required? 是一个可选的模型方法,它测试您是否希望对给定方案进行此验证。

    更新

    似乎 c.require_password_confirmation=false 选项是指 password_confirmation 属性不再是自动创建的,因此您需要以稍微不同的方式处理解决方案。手动创建虚拟属性和配置文件更新的特定情况的自定义验证。像这样:

    class User < ActiveRecord::Base
      attr_accessor :password_confirmation
    
      validate do |user|
        unless user.new_record?
          user.errors.add :password, "is required" if self.password.blank?
          user.errors.add :password_confirmation, "is required" if self.password_confirmation.blank?
          user.errors.add_to_base, "Password and confirmation must match" if self.password != self.password_confirmation
        end
      end
    end
    
    推荐文章