I'm trying to create a User
model for my Ruby on Rails
app that has a password
field that is not saved in the database, but for some reason, it's not being updated correctly.
class User < ActiveRecord::Base
attr :password
validates_presence_of :email, :password_digest
def password!
password_digest = Digest::SHA1.hexdigest(password)
end
def password?(password)
password_digest == Digest::SHA1.hexdigest(password)
end
end
I'm using a very basic form to update the email
and password
.
= form_for @user do |f|
-if @user.errors.any?
#error_explanation
%h2= "#{pluralize(@user.errors.count, "error")} prohibited this user from being saved:"
%ul
- @user.errors.full_messages.each do |msg|
%li= msg
.field
= f.label :email
= f.email_field :email, :required => true
.field
= f.label :password
= f.password_field :password, :required => true
.actions
= f.submit 'Save'
In my controller I'm trying to use the basic update mechanism, though I am willing to add more code if I absolutely have to.
class UsersController < ApplicationController
def create
@user = User.new(params[:user])
@user.password!
respond_to do |format|
if @user.save
format.html { redirect_to @user, notice: 'User was successfully created.' }
format.json { render json: @user, status: :created, location: @user }
else
format.html { render action: "new" }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
end
When this update is processed it throws a TypeError
with the message: can't convert nil into String
.
I've tried a few different ways to fix this, including manually setting the password
using params[:user][:password]
but it won't work. Can anyone spot the bug I'm missing?
In your password! method, you need to specify that you want to access the instance variable password_digest. Change to:
def password!
self.password_digest = Digest::SHA1.hexdigest(password)
end