我正在看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现在,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}
endUser对象有六个属性: 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和password_confirmation字段未定义。我该如何解决这个问题呢?
麦克
发布于 2012-05-05 07:41:06
attr_accessible只是告诉Rails允许在质量赋值中设置属性,如果属性不存在,它实际上不会创建属性。
您需要为password和password_confirmation使用attr_accessor,因为这些属性在数据库中没有对应的字段:
class User < ActiveRecord::Base
attr_accessor :password, :password_confirmation
attr_accessible :email, :name, :password, :password_confirmation
...
endhttps://stackoverflow.com/questions/10457439
复制相似问题