首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Ruby on Rails 3教程

Ruby on Rails 3教程
EN

Stack Overflow用户
提问于 2012-05-05 07:38:22
回答 1查看 281关注 0票数 2

我正在看Michael Hartl写的关于http://ruby.railstutorial.org/的教程。

我在第六章特别介绍了代码清单6.27,它看起来像这样:

代码语言:javascript
复制
    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对象如下所示:

代码语言:javascript
复制
    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测试中的代码时:

代码语言:javascript
复制
    @user = User.new(name: "Example User", email: "user@example.com", 
                     password: "foobar", password_confirmation: "foobar")

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

麦克

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-05-05 07:41:06

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

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

代码语言:javascript
复制
class User < ActiveRecord::Base
  attr_accessor :password, :password_confirmation
  attr_accessible :email, :name, :password, :password_confirmation
  ...
end
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10457439

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档