第9章(新增)Rails Tutorial控制台练习:#<class:0x00000004ab1dd8>

时间:2016-07-20 07:39:13

标签: ruby-on-rails railstutorial.org

我搜索了所有stackoverflow的答案,但仍然不知道该怎么做。 练习让我:

  

将用户分配给数据库中的第一个用户,并通过直接调用remember方法进行验证来验证。

我应该致电:

user.remember 

这给了我错误

undefined method `remember_token' for #<Class:0x00000004ab1dd8>

我做了:

rails generate migration add_remember_digest_to_users remember_digest:string 
rails db:migrate

user.rb:enter code here

    class User < ApplicationRecord
  before_save { email.downcase! }
  validates :name, presence: true, length: { maximum: 50 }
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[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 }

  # Returns the hash digest of the given string.
  def User.digest(string)
    cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
                                                  BCrypt::Engine::cost
    BCrypt::Password.create(string, cost: cost)
  end

  # Returns a random token.   Listing 9.2: Adding a method for generating     tokens.
  def User.new_token
    SecureRandom.urlsafe_base64
  end

  # Remembers a user in the database for use in persistent sessions.
  def remember      # Listing 9.3: Adding a remember method to the User     model. green
    self.remember_token = User.new_token
    update_attribute(:remember_digest, User.digest(remember_token))
  end
end

我运行'rails test',0次失败,0次错误,0次跳过!

1 个答案:

答案 0 :(得分:0)

您必须先将第一个用户分配给用户,然后再调用remember方法

你的方式是

  
    

user = User.first     user.remember