Ruby on Rails 3教程

mai*_*aik 2 ruby-on-rails

我正在阅读Michael Hartl的http://ruby.railstutorial.org/上的教程.

我在第六章专门编写代码6.27,如下所示:

    require 'spec_helper'

    describe User do

      before do
        @user = User.new(name: "Example User", email: "user@example.com", 
                         password: "foobar", password_confirmation: "foobar")
      end

      subject { @user }

      it { should respond_to(:name) }
      it { should respond_to(:email) }
      it { should respond_to(:password_digest) }
      it { should respond_to(:password) }
      it { should respond_to(:password_confirmation) }

      it { should be_valid }
    end
Run Code Online (Sandbox Code Playgroud)

现在,User对象如下所示:

    class User < ActiveRecord::Base
      attr_accessible :email, :name, :password, :password_confirmation
      before_save { |user| user.email = email.downcase }

      validates :name, presence: true, length: {maximum: 50}
      VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
      validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }, uniquenes  
      {case_sensitive: false}
    end
Run Code Online (Sandbox Code Playgroud)

User对象有六个属性:id,name,email,created_at,updated_at,password_digest.password_digest是存储散列密码的位置.但正如您所见,字段password和password_confirmation不在数据库中.只有password_digest是.作者声称我们不需要将它们存储在数据库中,而只是暂时在内存中创建它们.但是当我从rspec测试运行代码时:

    @user = User.new(name: "Example User", email: "user@example.com", 
                     password: "foobar", password_confirmation: "foobar")
Run Code Online (Sandbox Code Playgroud)

我收到错误告诉我字段密码和password_confirmation未定义.我该如何解决这个问题?

麦克风

pju*_*ble 5

attr_accessible 只是告诉Rails,允许在质量分配中设置属性,如果它们不存在,它实际上不会创建属性.

您需要使用attr_accessorfor password,password_confirmation因为这些属性在数据库中没有相应的字段:

class User < ActiveRecord::Base
  attr_accessor :password, :password_confirmation
  attr_accessible :email, :name, :password, :password_confirmation
  ...
end
Run Code Online (Sandbox Code Playgroud)