2

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: "[email protected]", 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: "[email protected]", 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

1 Answer 1

5

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 
Sign up to request clarification or add additional context in comments.

3 Comments

rails guys need to do something to give attr_accessible a different name. .. I have seen so many guys confusing attr_accessor and attr_accessible
ok I found the problem. I missed the line has_secure_password inside User class. I don't know why or how this works. Can someone please enlighten me?
You can see the source and documentation of has_secure_password here. It's a basic function which mixes a little bit of extra functionality into the model (an attr_reader :password and a setter which generates the encrypted password / password_digest automatically when the password property changes).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.