简体   繁体   English

如何在使用Rails的模型中设置虚拟属性?

[英]How to set a virtual attribute in model with Rails?

I have a model User with usual attributes email, email_confirmation, password, password_confirmation. 我有一个模型用户,具有通常的属性,电子邮件,电子邮件确认,密码,密码确认。 I use "has_secure_password" so the real attributes in the database are email and password_digest. 我使用“ has_secure_password”,因此数据库中的实际属性是email和password_digest。 However I would like to limit password length without spaces to 6 characters. 但是,我想将密码长度(不带空格)限制为6个字符。

Here is my model : 这是我的模特:

class User < ActiveRecord::Base
  before_validation :auto_strip_confirmation
  validates :email,       presence: true,
                          length: { maximum: MAX_SIZE_DEFAULT_INPUT_TEXT },
                          format: { with: VALID_EMAIL_REGEX },
                          uniqueness: { case_sensitive: false },
                          confirmation: true
  validates :email_confirmation, presence: true
  has_secure_password
  validates :password,    length: { minimum: MIN_SIZE_USER_PASSWORD,
                                    maximum: MAX_SIZE_USER_PASSWORD }

  private

    def auto_strip_confirmation
      self.password.strip!
      self.password_confirmation.strip!
    end
end

But I get this in console : 但是我在控制台中得到了这个:

 > user.password = user.password_confirmation = "a     "
 => "a     " 
 > user.valid?
  User Exists (0.8ms)  SELECT 1 AS one FROM "users" WHERE LOWER("users"."email") = LOWER('user@example.com') LIMIT 1
 => true 

Thanks for your help. 谢谢你的帮助。

After reload, my code actually works in console : user.valid? 重新加载后,我的代码实际上可以在console中工作:user.valid? => false (thanks surendran). =>否(感谢surendran)。 But my initial problem was in my tests : I thought I could not set virtual attributes because of the error message "undefined method `strip!' 但是我的最初问题是在测试中:我以为我无法设置虚拟属性,因为错误消息为“未定义的方法'strip!'”。 for nil:NilClass". 为nil:NilClass”。 But I forgot I test if my user is valid when password is nil, nearly like this : 但是我忘了在密码为nil时测试用户是否有效,几乎是这样的:

before { user.password = nil) }
it { should_not be_valid }

before_validation comes before this test so he tries to strip a nil object. before_validation在此测试之前进行,因此他尝试剥离nil对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM