Ruby on Rails - 用户对象显示nil字段,即使它们已填充

时间:2016-08-14 03:26:01

标签: ruby-on-rails ruby model-view-controller login model

我有一个奇怪的问题,让我的用户注册在Rails中工作。当我创建一个用户时,它将显示其所有字段,但password_digest为nil,但是当我键入类似" u.email"之类的内容时,电子邮件将显示出来。但是,它并不想保存用户,我认为因为它认为它不能满足所有验证要求。

一些铁路控制台摆弄:

irb(main):003:0> u = User.new({username: "askddkasd", email: "a@a.a", 
    password: "meowmeowmeow", password_confirmation: "meowmeowmeow"})
=> #<User id: nil, username: nil, email: nil, password_digest: 
    "$2a$10$eWhQdOCLXfmcGrrRdigSFeENUeAEaQ6xJ7U08k7g3gZ...", salt: nil>
irb(main):002:0> u.save
    (0.2ms)  BEGIN
      User Exists (0.3ms)  SELECT  1 AS one FROM `users` WHERE `users`.`username` = BINARY 'askddkasd' LIMIT 1
      User Exists (0.2ms)  SELECT  1 AS one FROM `users` WHERE `users`.`email` = BINARY 'a@a.a' LIMIT 1
    (0.1ms)  ROLLBACK
=> false
irb(main):022:0> u.username
=> "askddkasd"
irb(main):023:0> u.email
=> "a@a.a"

如您所见,字段显示为nil,但我可以访问它们的值。 这是我的用户模型:

class User < ApplicationRecord
    has_secure_password

    attr_accessor :username, :email, :password, :password_confirmation

    validates :username, :presence => true, :uniqueness => true, :length => { :in => 3..20 }
    validates :email, :presence => true, :uniqueness => true
    validates :password, :confirmation => true #password_confirmation attr
    validates_length_of :password, :in => 6..20, :on => :create

    after_save :clear_password

    def password=(password)
        self.password_digest = BCrypt::Password.create(password)
    end

    def is_password?(password)
        BCrypt::Password.new(self.password_digest) == password
    end

    def clear_password
        self.password = nil
    end

    def self.authenticate(username_or_email="", login_password="")
      if username_or_email.include? '@'
        user = User.find_by_email(username_or_email)
      else
        user = User.find_by_username(username_or_email)
      end

      if user && user.is_password?(login_password)
        return user
      end
      return false
    end
end

以前有人有这个问题吗?如果是这样,你是如何解决的?

更新:可能是因为我有用户名和电子邮件作为访问者?那么这些价值实际上并没有到用户名/电子邮件字段存储在数据库中?

1 个答案:

答案 0 :(得分:0)

它在日志

中的此语句之后回滚的事实
User Exists (0.2ms)  SELECT  1 AS one FROM `users` WHERE `users`.`email` = BINARY 'a@a.a' LIMIT 1

让我觉得数据库中已有一个用户使用此电子邮件地址。您可以通过调用u.valid?然后u.errors来确定问题所在。