Ruby on Rails 3教程

时间:2012-05-04 23:38:22

标签: ruby-on-rails

我正在阅读迈克尔·哈特尔的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

现在,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

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")

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

麦克

1 个答案:

答案 0 :(得分:5)

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

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

class User < ActiveRecord::Base
  attr_accessor :password, :password_confirmation
  attr_accessible :email, :name, :password, :password_confirmation
  ...
end