简体   繁体   中英

Ruby on Rails 3 Tutorial

I'm going through the tutorial on http://ruby.railstutorial.org/ by Michael Hartl.

I'm on chapter six specifically code listing 6.27 which looks like this:

    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

Now the User object looks like this:

    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

The User object has six attributes: id, name, email, created_at, updated_at, password_digest. The password_digest is where the hashed password is stored. But as you can see the fields password and password_confirmation are not in the database. Only password_digest is. The author claims we don't need to store them in a database but only create them temporarily in memory. But when i run the code from the rspec test:

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

I get an error telling me fields password and password_confirmation are undefined. How do I get around this?

mike

attr_accessible just tells Rails the properties are allowed to be set in mass-assignments, it doesn't actually create the properties if they don't exist.

You need to use attr_accessor for password and password_confirmation because these properties don't have corresponding fields in the database:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM