dbslone
dbslone

Reputation: 2034

Rails Undefined Method

I am completely new to Ruby and trying to learn the language. I am using the book Agile Web Development with Rails and in the chapter about creating using accounts, I keep receiving the error:

Processing by UsersController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"Ykj1a4971bgeEXuftslIgPErK67VTvPlTpcg//Wx8R8=", "user"=>{"name"=>"testaccount", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Create User"}
Completed 500 Internal Server Error in 16ms

NoMethodError (undefined method `salt=' for #<User:0x00000009008b70>):
  app/models/user.rb:41:in `generate_salt'
  app/models/user.rb:29:in `password='
  app/controllers/users_controller.rb:43:in `new'
  app/controllers/users_controller.rb:43:in `create'

Below is the code in my user.rb file:

require 'digest/sha2'

class User < ActiveRecord::Base
  validates :name, :presence => true, :uniqueness => true

  validates :password, :confirmation => true
  attr_accessor :password_confirmation
  attr_reader   :password

  validate  :password_must_be_present

  def User.authenticate(name, password)
    if user = find_by_name(name)
      if user.hashed_password == encrypt_password(password, user.salt)
        user
      end
    end
  end

  def User.encrypt_password(password, salt)
    Digest::SHA2.hexdigest(password + "wibble" + salt)
  end

  # 'password' is a virtual attribute
  def password=(password)
    @password = password

    if password.present?
      generate_salt
      self.hashed_password = self.class.encrypt_password(password, salt)
    end
  end

  private

    def password_must_be_present
      errors.add(:password, "Missing password") unless hashed_password.present?
    end

    def generate_salt
      self.salt = self.object_id.to_s + rand.to_s
    end
end

Any ideas what could be causing my problem. If you need more information let me know which files to list the code from.

Upvotes: 0

Views: 1692

Answers (2)

ardavis
ardavis

Reputation: 9895

The more I learn about Ruby and Rails, the more I realize that I don't write much of my own code.

I believe using something like Devise would greatly ease your pain in encrypting your own stuff.

This is a suggestion that may assist you greatly in this problem and more to come.

Upvotes: 3

Sam 山
Sam 山

Reputation: 42863

It's because salt is not defined in that model.

You already have this:

attr_accessor :password_confirmation

What you can do is add this below that line:

attr_accessor :salt

And that should work.

Upvotes: -1

Related Questions