2016-04-12 14 views
0

Michael Hartlのチュートリアルでは、次のことが述べられています。あなたは9.10をリストすると、新しいユーザーが空のパスワードでサインアップすることが可能かもしれないと心配している場合には空のパスワードでアクションを更新

class User < ActiveRecord::Base 
attr_accessor :remember_token 
before_save { self.email = email.downcase } 
validates :name, presence: true, length: { maximum: 50 } 
VALID_EMAIL_REGEX = /\A[\w+\-.][email protected][a-z\d\-.]+\.[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 

end 

、セクションからのリコールはhas_secure_passwordが、具体的nilのパスワードをキャッチし、別の存在の検証が含まれていること6.3.3。

私の質問は、テストが合格する場合、has_secure_password検証はどのように機能していますか?私は理解していない、明らかにhas_secure_passwordの検証は空のパスワードをバイパスするためにこのルールを "キャッチ"していない。

さらに、空のパスワードを設定してユーザーに保存しないようにするにはどうすればよいですか?私を助けてください。

答えて

0

あなたはドキュメントhereを確認することができますが、それはソースコードによると、細部のすべてを説明し

:あなたはhas_secure_password(validations: false)を呼び出していない場合

def has_secure_password 
    ..... 
    if options.fetch(:validations, true) 
    include ActiveModel::Validations 

    # This ensures the model has a password by checking whether the password_digest 
    # is present, so that this works with both new and existing records. However, 
    # when there is an error, the message is added to the password attribute instead 
    # so that the error message will make sense to the end-user. 
    validate do |record| 
     record.errors.add(:password, :blank) unless record.password_digest.present? 
    end 

    validates_length_of :password, maximum: ActiveModel::SecurePassword::MAX_PASSWORD_LENGTH_ALLOWED 
    validates_confirmation_of :password, allow_blank: true 
    end 
    .......... 
end 

検証の3種類が追加されます。

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

が検証された値がnilのとき:allow_nilオプションは、検証をスキップ:私は通過テストの理由があると思います。レールは ユーザーに空のパスワードを設定して保存しないように知っているか

を追加する

私はparams[:user][:password]がnil

ブランクではないので、それはだと思います
関連する問題